home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1998 November / Freeware November 1998.img / dist / fw_emacs.idb / usr / freeware / share / emacs / 19.34 / lisp / files.el.z / files.el
Lisp/Scheme  |  1998-10-27  |  107KB  |  2,731 lines

  1. ;;; files.el --- file input and output commands for Emacs
  2.  
  3. ;; Copyright (C) 1985, 86, 87, 92, 93,
  4. ;;         94, 95, 1996 Free Software Foundation, Inc.
  5.  
  6. ;; Maintainer: FSF
  7.  
  8. ;; This file is part of GNU Emacs.
  9.  
  10. ;; GNU Emacs is free software; you can redistribute it and/or modify
  11. ;; it under the terms of the GNU General Public License as published by
  12. ;; the Free Software Foundation; either version 2, or (at your option)
  13. ;; any later version.
  14.  
  15. ;; GNU Emacs is distributed in the hope that it will be useful,
  16. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  18. ;; GNU General Public License for more details.
  19.  
  20. ;; You should have received a copy of the GNU General Public License
  21. ;; along with GNU Emacs; see the file COPYING.  If not, write to the
  22. ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  23. ;; Boston, MA 02111-1307, USA.
  24.  
  25. ;;; Commentary:
  26.  
  27. ;; Defines most of Emacs's file- and directory-handling functions,
  28. ;; including basic file visiting, backup generation, link handling,
  29. ;; ITS-id version control, load- and write-hook handling, and the like.
  30.  
  31. ;;; Code:
  32.  
  33. (defconst delete-auto-save-files t
  34.   "*Non-nil means delete auto-save file when a buffer is saved or killed.")
  35.  
  36. (defconst directory-abbrev-alist
  37.   nil
  38.   "*Alist of abbreviations for file directories.
  39. A list of elements of the form (FROM . TO), each meaning to replace
  40. FROM with TO when it appears in a directory name.  This replacement is
  41. done when setting up the default directory of a newly visited file.
  42. *Every* FROM string should start with `^'.
  43.  
  44. Do not use `~' in the TO strings.
  45. They should be ordinary absolute directory names.
  46.  
  47. Use this feature when you have directories which you normally refer to
  48. via absolute symbolic links.  Make TO the name of the link, and FROM
  49. the name it is linked to.")
  50.  
  51. ;;; Turn off backup files on VMS since it has version numbers.
  52. (defconst make-backup-files (not (eq system-type 'vax-vms))
  53.   "*Non-nil means make a backup of a file the first time it is saved.
  54. This can be done by renaming the file or by copying.
  55.  
  56. Renaming means that Emacs renames the existing file so that it is a
  57. backup file, then writes the buffer into a new file.  Any other names
  58. that the old file had will now refer to the backup file.  The new file
  59. is owned by you and its group is defaulted.
  60.  
  61. Copying means that Emacs copies the existing file into the backup
  62. file, then writes the buffer on top of the existing file.  Any other
  63. names that the old file had will now refer to the new (edited) file.
  64. The file's owner and group are unchanged.
  65.  
  66. The choice of renaming or copying is controlled by the variables
  67. `backup-by-copying', `backup-by-copying-when-linked' and
  68. `backup-by-copying-when-mismatch'.  See also `backup-inhibited'.")
  69.  
  70. ;; Do this so that local variables based on the file name
  71. ;; are not overridden by the major mode.
  72. (defvar backup-inhibited nil
  73.   "Non-nil means don't make a backup, regardless of the other parameters.
  74. This variable is intended for use by making it local to a buffer.
  75. But it is local only if you make it local.")
  76. (put 'backup-inhibited 'permanent-local t)
  77.  
  78. (defconst backup-by-copying nil
  79.  "*Non-nil means always use copying to create backup files.
  80. See documentation of variable `make-backup-files'.")
  81.  
  82. (defconst backup-by-copying-when-linked nil
  83.  "*Non-nil means use copying to create backups for files with multiple names.
  84. This causes the alternate names to refer to the latest version as edited.
  85. This variable is relevant only if `backup-by-copying' is nil.")
  86.  
  87. (defconst backup-by-copying-when-mismatch nil
  88.   "*Non-nil means create backups by copying if this preserves owner or group.
  89. Renaming may still be used (subject to control of other variables)
  90. when it would not result in changing the owner or group of the file;
  91. that is, for files which are owned by you and whose group matches
  92. the default for a new file created there by you.
  93. This variable is relevant only if `backup-by-copying' is nil.")
  94.  
  95. (defvar backup-enable-predicate
  96.   '(lambda (name)
  97.      (or (< (length name) 5)
  98.      (not (string-equal "/tmp/" (substring name 0 5)))))
  99.   "Predicate that looks at a file name and decides whether to make backups.
  100. Called with an absolute file name as argument, it returns t to enable backup.")
  101.  
  102. (defconst buffer-offer-save nil
  103.   "*Non-nil in a buffer means offer to save the buffer on exit
  104. even if the buffer is not visiting a file.
  105. Automatically local in all buffers.")
  106. (make-variable-buffer-local 'buffer-offer-save)
  107.  
  108. (defconst find-file-existing-other-name nil
  109.   "*Non-nil means find a file under alternative names, in existing buffers.
  110. This means if any existing buffer is visiting the file you want
  111. under another name, you get the existing buffer instead of a new buffer.")
  112.  
  113. (defconst find-file-visit-truename nil
  114.   "*Non-nil means visit a file under its truename.
  115. The truename of a file is found by chasing all links
  116. both at the file level and at the levels of the containing directories.")
  117.  
  118. (defvar buffer-file-number nil
  119.   "The device number and file number of the file visited in the current buffer.
  120. The value is a list of the form (FILENUM DEVNUM).
  121. This pair of numbers uniquely identifies the file.
  122. If the buffer is visiting a new file, the value is nil.")
  123. (make-variable-buffer-local 'buffer-file-number)
  124. (put 'buffer-file-number 'permanent-local t)
  125.  
  126. (defvar buffer-file-numbers-unique (not (memq system-type '(windows-nt)))
  127.   "Non-nil means that buffer-file-number uniquely identifies files.")
  128.  
  129. (defconst file-precious-flag nil
  130.   "*Non-nil means protect against I/O errors while saving files.
  131. Some modes set this non-nil in particular buffers.
  132.  
  133. This feature works by writing the new contents into a temporary file
  134. and then renaming the temporary file to replace the original.
  135. In this way, any I/O error in writing leaves the original untouched,
  136. and there is never any instant where the file is nonexistent.
  137.  
  138. Note that this feature forces backups to be made by copying.
  139. Yet, at the same time, saving a precious file
  140. breaks any hard links between it and other files.")
  141.  
  142. (defvar version-control nil
  143.   "*Control use of version numbers for backup files.
  144. t means make numeric backup versions unconditionally.
  145. nil means make them for files that have some already.
  146. `never' means do not make them.")
  147.  
  148. (defvar dired-kept-versions 2
  149.   "*When cleaning directory, number of versions to keep.")
  150.  
  151. (defvar delete-old-versions nil
  152.   "*If t, delete excess backup versions silently.
  153. If nil, ask confirmation.  Any other value prevents any trimming.")
  154.  
  155. (defvar kept-old-versions 2
  156.   "*Number of oldest versions to keep when a new numbered backup is made.")
  157.  
  158. (defvar kept-new-versions 2
  159.   "*Number of newest versions to keep when a new numbered backup is made.
  160. Includes the new backup.  Must be > 0")
  161.  
  162. (defconst require-final-newline nil
  163.   "*Value of t says silently ensure a file ends in a newline when it is saved.
  164. Non-nil but not t says ask user whether to add a newline when there isn't one.
  165. nil means don't add newlines.")
  166.  
  167. (defconst auto-save-default t
  168.   "*Non-nil says by default do auto-saving of every file-visiting buffer.")
  169.  
  170. (defconst auto-save-visited-file-name nil
  171.   "*Non-nil says auto-save a buffer in the file it is visiting, when practical.
  172. Normally auto-save files are written under other names.")
  173.  
  174. (defconst save-abbrevs nil
  175.   "*Non-nil means save word abbrevs too when files are saved.
  176. Loading an abbrev file sets this to t.")
  177.  
  178. (defconst find-file-run-dired t
  179.   "*Non-nil says run dired if `find-file' is given the name of a directory.")
  180.  
  181. ;;;It is not useful to make this a local variable.
  182. ;;;(put 'find-file-not-found-hooks 'permanent-local t)
  183. (defvar find-file-not-found-hooks nil
  184.   "List of functions to be called for `find-file' on nonexistent file.
  185. These functions are called as soon as the error is detected.
  186. `buffer-file-name' is already set up.
  187. The functions are called in the order given until one of them returns non-nil.")
  188.  
  189. ;;;It is not useful to make this a local variable.
  190. ;;;(put 'find-file-hooks 'permanent-local t)
  191. (defvar find-file-hooks nil
  192.   "List of functions to be called after a buffer is loaded from a file.
  193. The buffer's local variables (if any) will have been processed before the
  194. functions are called.")
  195.  
  196. (defvar write-file-hooks nil
  197.   "List of functions to be called before writing out a buffer to a file.
  198. If one of them returns non-nil, the file is considered already written
  199. and the rest are not called.
  200. These hooks are considered to pertain to the visited file.
  201. So this list is cleared if you change the visited file name.
  202.  
  203. Don't make this variable buffer-local; instead, use `local-write-file-hooks'.
  204. See also `write-contents-hooks'.")
  205. ;;; However, in case someone does make it local...
  206. (put 'write-file-hooks 'permanent-local t)
  207.  
  208. (defvar local-write-file-hooks nil
  209.   "Just like `write-file-hooks', except intended for per-buffer use.
  210. The functions in this list are called before the ones in
  211. `write-file-hooks'.
  212.  
  213. This variable is meant to be used for hooks that have to do with a
  214. particular visited file.  Therefore, it is a permanent local, so that
  215. changing the major mode does not clear it.  However, calling
  216. `set-visited-file-name' does clear it.")
  217. (make-variable-buffer-local 'local-write-file-hooks)
  218. (put 'local-write-file-hooks 'permanent-local t)
  219.  
  220. (defvar write-contents-hooks nil
  221.   "List of functions to be called before writing out a buffer to a file.
  222. If one of them returns non-nil, the file is considered already written
  223. and the rest are not called.
  224.  
  225. This variable is meant to be used for hooks that pertain to the
  226. buffer's contents, not to the particular visited file; thus,
  227. `set-visited-file-name' does not clear this variable; but changing the
  228. major mode does clear it.
  229.  
  230. This variable automatically becomes buffer-local whenever it is set.
  231. If you use `add-hooks' to add elements to the list, use nil for the
  232. LOCAL argument.
  233.  
  234. See also `write-file-hooks'.")
  235. (make-variable-buffer-local 'write-contents-hooks)
  236.  
  237. (defconst enable-local-variables t
  238.   "*Control use of local-variables lists in files you visit.
  239. The value can be t, nil or something else.
  240. A value of t means local-variables lists are obeyed;
  241. nil means they are ignored; anything else means query.
  242.  
  243. The command \\[normal-mode] always obeys local-variables lists
  244. and ignores this variable.")
  245.  
  246. (defconst enable-local-eval 'maybe
  247.   "*Control processing of the \"variable\" `eval' in a file's local variables.
  248. The value can be t, nil or something else.
  249. A value of t means obey `eval' variables;
  250. nil means ignore them; anything else means query.
  251.  
  252. The command \\[normal-mode] always obeys local-variables lists
  253. and ignores this variable.")
  254.  
  255. ;; Avoid losing in versions where CLASH_DETECTION is disabled.
  256. (or (fboundp 'lock-buffer)
  257.     (defalias 'lock-buffer 'ignore))
  258. (or (fboundp 'unlock-buffer)
  259.     (defalias 'unlock-buffer 'ignore))
  260.  
  261. ;; This hook function provides support for ange-ftp host name
  262. ;; completion.  It runs the usual ange-ftp hook, but only for
  263. ;; completion operations.  Having this here avoids the need
  264. ;; to load ange-ftp when it's not really in use.
  265. (defun ange-ftp-completion-hook-function (op &rest args)
  266.   (if (memq op '(file-name-completion file-name-all-completions))
  267.       (apply 'ange-ftp-hook-function op args)
  268.     (let ((inhibit-file-name-handlers
  269.        (cons 'ange-ftp-completion-hook-function
  270.          (and (eq inhibit-file-name-operation op)
  271.               inhibit-file-name-handlers)))
  272.       (inhibit-file-name-operation op))
  273.       (apply op args))))
  274.  
  275. (defun convert-standard-filename (filename)
  276.   "Convert a standard file's name to something suitable for the current OS.
  277. This function's standard definition is trivial; it just returns the argument.
  278. However, on some systems, the function is redefined
  279. with a definition that really does change some file names."
  280.   filename)
  281.  
  282. (defun pwd ()
  283.   "Show the current default directory."
  284.   (interactive nil)
  285.   (message "Directory %s" default-directory))
  286.  
  287. (defvar cd-path nil
  288.   "Value of the CDPATH environment variable, as a list.
  289. Not actually set up until the first time you you use it.")
  290.  
  291. (defvar path-separator ":"
  292.   "Character used to separate concatenated paths.")
  293.  
  294. (defun parse-colon-path (cd-path)
  295.   "Explode a colon-separated list of paths into a string list."
  296.   (and cd-path
  297.        (let (cd-prefix cd-list (cd-start 0) cd-colon)
  298.      (setq cd-path (concat cd-path path-separator))
  299.      (while (setq cd-colon (string-match path-separator cd-path cd-start))
  300.        (setq cd-list
  301.          (nconc cd-list
  302.             (list (if (= cd-start cd-colon)
  303.                    nil
  304.                 (substitute-in-file-name
  305.                  (file-name-as-directory
  306.                   (substring cd-path cd-start cd-colon)))))))
  307.        (setq cd-start (+ cd-colon 1)))
  308.      cd-list)))
  309.  
  310. (defun cd-absolute (dir)
  311.   "Change current directory to given absolute file name DIR."
  312.   ;; Put the name into directory syntax now,
  313.   ;; because otherwise expand-file-name may give some bad results.
  314.   (if (not (eq system-type 'vax-vms))
  315.       (setq dir (file-name-as-directory dir)))
  316.   (setq dir (abbreviate-file-name (expand-file-name dir)))
  317.   (if (not (file-directory-p dir))
  318.       (error "%s is not a directory" dir)
  319.     (if (file-executable-p dir)
  320.     (setq default-directory dir)
  321.       (error "Cannot cd to %s:  Permission denied" dir))))
  322.  
  323. (defun cd (dir)
  324.   "Make DIR become the current buffer's default directory.
  325. If your environment includes a `CDPATH' variable, try each one of that
  326. colon-separated list of directories when resolving a relative directory name."
  327.   (interactive
  328.    (list (read-file-name "Change default directory: "
  329.              default-directory default-directory
  330.              (and (member cd-path '(nil ("./")))
  331.                   (null (getenv "CDPATH"))))))
  332.   (if (file-name-absolute-p dir)
  333.       (cd-absolute (expand-file-name dir))
  334.     (if (null cd-path)
  335.     (let ((trypath (parse-colon-path (getenv "CDPATH"))))
  336.       (setq cd-path (or trypath (list "./")))))
  337.     (if (not (catch 'found
  338.            (mapcar
  339.         (function (lambda (x)
  340.                 (let ((f (expand-file-name (concat x dir))))
  341.                   (if (file-directory-p f)
  342.                   (progn
  343.                     (cd-absolute f)
  344.                     (throw 'found t))))))
  345.         cd-path)
  346.            nil))
  347.     (error "No such directory found via CDPATH environment variable"))))
  348.  
  349. (defun load-file (file)
  350.   "Load the Lisp file named FILE."
  351.   (interactive "fLoad file: ")
  352.   (load (expand-file-name file) nil nil t))
  353.  
  354. (defun load-library (library)
  355.   "Load the library named LIBRARY.
  356. This is an interface to the function `load'."
  357.   (interactive "sLoad library: ")
  358.   (load library))
  359.  
  360. (defun file-local-copy (file &optional buffer)
  361.   "Copy the file FILE into a temporary file on this machine.
  362. Returns the name of the local copy, or nil, if FILE is directly
  363. accessible."
  364.   (let ((handler (find-file-name-handler file 'file-local-copy)))
  365.     (if handler
  366.     (funcall handler 'file-local-copy file)
  367.       nil)))
  368.  
  369. (defun file-truename (filename &optional counter prev-dirs)
  370.   "Return the truename of FILENAME, which should be absolute.
  371. The truename of a file name is found by chasing symbolic links
  372. both at the level of the file and at the level of the directories
  373. containing it, until no links are left at any level.
  374.  
  375. The arguments COUNTER and PREV-DIRS are used only in recursive calls.
  376. Do not specify them in other calls."
  377.   ;; COUNTER can be a cons cell whose car is the count of how many more links
  378.   ;; to chase before getting an error.
  379.   ;; PREV-DIRS can be a cons cell whose car is an alist
  380.   ;; of truenames we've just recently computed.
  381.  
  382.   ;; The last test looks dubious, maybe `+' is meant here?  --simon.
  383.   (if (or (string= filename "") (string= filename "~")
  384.       (and (string= (substring filename 0 1) "~")
  385.            (string-match "~[^/]*" filename)))
  386.       (progn
  387.     (setq filename (expand-file-name filename))
  388.     (if (string= filename "")
  389.         (setq filename "/"))))
  390.   (or counter (setq counter (list 100)))
  391.   (let (done
  392.     ;; For speed, remove the ange-ftp completion handler from the list.
  393.     ;; We know it's not needed here.
  394.     ;; For even more speed, do this only on the outermost call.
  395.     (file-name-handler-alist
  396.      (if prev-dirs file-name-handler-alist
  397.        (let ((tem (copy-sequence file-name-handler-alist)))
  398.          (delq (rassq 'ange-ftp-completion-hook-function tem) tem)))))
  399.     (or prev-dirs (setq prev-dirs (list nil)))
  400.     ;; If this file directly leads to a link, process that iteratively
  401.     ;; so that we don't use lots of stack.
  402.     (while (not done)
  403.       (setcar counter (1- (car counter)))
  404.       (if (< (car counter) 0)
  405.       (error "Apparent cycle of symbolic links for %s" filename))
  406.       (let ((handler (find-file-name-handler filename 'file-truename)))
  407.     ;; For file name that has a special handler, call handler.
  408.     ;; This is so that ange-ftp can save time by doing a no-op.
  409.     (if handler
  410.         (setq filename (funcall handler 'file-truename filename)
  411.           done t)
  412.       (let ((dir (or (file-name-directory filename) default-directory))
  413.         target dirfile)
  414.         ;; Get the truename of the directory.
  415.         (setq dirfile (directory-file-name dir))
  416.         ;; If these are equal, we have the (or a) root directory.
  417.         (or (string= dir dirfile)
  418.         ;; If this is the same dir we last got the truename for,
  419.         ;; save time--don't recalculate.
  420.         (if (assoc dir (car prev-dirs))
  421.             (setq dir (cdr (assoc dir (car prev-dirs))))
  422.           (let ((old dir)
  423.             (new (file-name-as-directory (file-truename dirfile counter prev-dirs))))
  424.             (setcar prev-dirs (cons (cons old new) (car prev-dirs)))
  425.             (setq dir new))))
  426.         (if (equal ".." (file-name-nondirectory filename))
  427.         (setq filename
  428.               (directory-file-name (file-name-directory (directory-file-name dir)))
  429.               done t)
  430.           (if (equal "." (file-name-nondirectory filename))
  431.           (setq filename (directory-file-name dir)
  432.             done t)
  433.         ;; Put it back on the file name.
  434.         (setq filename (concat dir (file-name-nondirectory filename)))
  435.         ;; Is the file name the name of a link?
  436.         (setq target (file-symlink-p filename))
  437.         (if target
  438.             ;; Yes => chase that link, then start all over
  439.             ;; since the link may point to a directory name that uses links.
  440.             ;; We can't safely use expand-file-name here
  441.             ;; since target might look like foo/../bar where foo
  442.             ;; is itself a link.  Instead, we handle . and .. above.
  443.             (setq filename
  444.               (if (file-name-absolute-p target)
  445.                   target
  446.                 (concat dir target))
  447.               done nil)
  448.           ;; No, we are done!
  449.           (setq done t))))))))
  450.     filename))
  451.  
  452. (defun file-chase-links (filename)
  453.   "Chase links in FILENAME until a name that is not a link.
  454. Does not examine containing directories for links,
  455. unlike `file-truename'."
  456.   (let (tem (count 100) (newname filename))
  457.     (while (setq tem (file-symlink-p newname))
  458.       (if (= count 0)
  459.       (error "Apparent cycle of symbolic links for %s" filename))
  460.       ;; In the context of a link, `//' doesn't mean what Emacs thinks.
  461.       (while (string-match "//+" tem)
  462.     (setq tem (concat (substring tem 0 (1+ (match-beginning 0)))
  463.               (substring tem (match-end 0)))))
  464.       ;; Handle `..' by hand, since it needs to work in the
  465.       ;; target of any directory symlink.
  466.       ;; This code is not quite complete; it does not handle
  467.       ;; embedded .. in some cases such as ./../foo and foo/bar/../../../lose.
  468.       (while (string-match "\\`\\.\\./" tem)
  469.     (setq tem (substring tem 3))
  470.     (setq newname (file-name-as-directory
  471.                ;; Do the .. by hand.
  472.                (directory-file-name
  473.             (file-name-directory
  474.              ;; Chase links in the default dir of the symlink.
  475.              (file-chase-links
  476.               (directory-file-name
  477.                (file-name-directory newname))))))))
  478.       (setq newname (expand-file-name tem (file-name-directory newname)))
  479.       (setq count (1- count)))
  480.     newname))
  481.  
  482. (defun switch-to-buffer-other-window (buffer)
  483.   "Select buffer BUFFER in another window."
  484.   (interactive "BSwitch to buffer in other window: ")
  485.   (let ((pop-up-windows t))
  486.     (pop-to-buffer buffer t)))
  487.  
  488. (defun switch-to-buffer-other-frame (buffer)
  489.   "Switch to buffer BUFFER in another frame."
  490.   (interactive "BSwitch to buffer in other frame: ")
  491.   (let ((pop-up-frames t))
  492.     (pop-to-buffer buffer t)
  493.     (raise-frame (window-frame (selected-window)))))
  494.  
  495. (defun find-file (filename)
  496.   "Edit file FILENAME.
  497. Switch to a buffer visiting file FILENAME,
  498. creating one if none already exists."
  499.   (interactive "FFind file: ")
  500.   (switch-to-buffer (find-file-noselect filename)))
  501.  
  502. (defun find-file-other-window (filename)
  503.   "Edit file FILENAME, in another window.
  504. May create a new window, or reuse an existing one.
  505. See the function `display-buffer'."
  506.   (interactive "FFind file in other window: ")
  507.   (switch-to-buffer-other-window (find-file-noselect filename)))
  508.  
  509. (defun find-file-other-frame (filename)
  510.   "Edit file FILENAME, in another frame.
  511. May create a new frame, or reuse an existing one.
  512. See the function `display-buffer'."
  513.   (interactive "FFind file in other frame: ")
  514.   (switch-to-buffer-other-frame (find-file-noselect filename)))
  515.  
  516. (defun find-file-read-only (filename)
  517.   "Edit file FILENAME but don't allow changes.
  518. Like \\[find-file] but marks buffer as read-only.
  519. Use \\[toggle-read-only] to permit editing."
  520.   (interactive "fFind file read-only: ")
  521.   (find-file filename)
  522.   (setq buffer-read-only t)
  523.   (current-buffer))
  524.  
  525. (defun find-file-read-only-other-window (filename)
  526.   "Edit file FILENAME in another window but don't allow changes.
  527. Like \\[find-file-other-window] but marks buffer as read-only.
  528. Use \\[toggle-read-only] to permit editing."
  529.   (interactive "fFind file read-only other window: ")
  530.   (find-file-other-window filename)
  531.   (setq buffer-read-only t)
  532.   (current-buffer))
  533.  
  534. (defun find-file-read-only-other-frame (filename)
  535.   "Edit file FILENAME in another frame but don't allow changes.
  536. Like \\[find-file-other-frame] but marks buffer as read-only.
  537. Use \\[toggle-read-only] to permit editing."
  538.   (interactive "fFind file read-only other frame: ")
  539.   (find-file-other-frame filename)
  540.   (setq buffer-read-only t)
  541.   (current-buffer))
  542.  
  543. (defun find-alternate-file-other-window (filename)
  544.   "Find file FILENAME as a replacement for the file in the next window.
  545. This command does not select that window."
  546.   (interactive
  547.    (save-selected-window
  548.      (other-window 1)
  549.      (let ((file buffer-file-name)
  550.        (file-name nil)
  551.        (file-dir nil))
  552.        (and file
  553.         (setq file-name (file-name-nondirectory file)
  554.           file-dir (file-name-directory file)))
  555.        (list (read-file-name
  556.           "Find alternate file: " file-dir nil nil file-name)))))
  557.   (if (one-window-p)
  558.       (find-file-other-window filename)
  559.     (save-selected-window
  560.       (other-window 1)
  561.       (find-alternate-file filename))))
  562.  
  563. (defun find-alternate-file (filename)
  564.   "Find file FILENAME, select its buffer, kill previous buffer.
  565. If the current buffer now contains an empty file that you just visited
  566. \(presumably by mistake), use this command to visit the file you really want."
  567.   (interactive
  568.    (let ((file buffer-file-name)
  569.      (file-name nil)
  570.      (file-dir nil))
  571.      (and file
  572.       (setq file-name (file-name-nondirectory file)
  573.         file-dir (file-name-directory file)))
  574.      (list (read-file-name
  575.         "Find alternate file: " file-dir nil nil file-name))))
  576.   (and (buffer-modified-p) (buffer-file-name)
  577.        ;; (not buffer-read-only)
  578.        (not (yes-or-no-p (format "Buffer %s is modified; kill anyway? "
  579.                  (buffer-name))))
  580.        (error "Aborted"))
  581.   (let ((obuf (current-buffer))
  582.     (ofile buffer-file-name)
  583.     (onum buffer-file-number)
  584.     (otrue buffer-file-truename)
  585.     (oname (buffer-name)))
  586.     (if (get-buffer " **lose**")
  587.     (kill-buffer " **lose**"))
  588.     (rename-buffer " **lose**")
  589.     (unwind-protect
  590.     (progn
  591.       (unlock-buffer)
  592.       (setq buffer-file-name nil)
  593.       (setq buffer-file-number nil)
  594.       (setq buffer-file-truename nil)
  595.       (find-file filename))
  596.       (cond ((eq obuf (current-buffer))
  597.          (setq buffer-file-name ofile)
  598.          (setq buffer-file-number onum)
  599.          (setq buffer-file-truename otrue)
  600.          (lock-buffer)
  601.          (rename-buffer oname))))
  602.     (or (eq (current-buffer) obuf)
  603.     (kill-buffer obuf))))
  604.  
  605. (defun create-file-buffer (filename)
  606.   "Create a suitably named buffer for visiting FILENAME, and return it.
  607. FILENAME (sans directory) is used unchanged if that name is free;
  608. otherwise a string <2> or <3> or ... is appended to get an unused name."
  609.   (let ((lastname (file-name-nondirectory filename)))
  610.     (if (string= lastname "")
  611.     (setq lastname filename))
  612.     (generate-new-buffer lastname)))
  613.  
  614. (defun generate-new-buffer (name)
  615.   "Create and return a buffer with a name based on NAME.
  616. Choose the buffer's name using `generate-new-buffer-name'."
  617.   (get-buffer-create (generate-new-buffer-name name)))
  618.  
  619. (defconst automount-dir-prefix "^/tmp_mnt/"
  620.   "Regexp to match the automounter prefix in a directory name.")
  621.  
  622. (defvar abbreviated-home-dir nil
  623.   "The user's homedir abbreviated according to `directory-abbrev-list'.")
  624.  
  625. (defun abbreviate-file-name (filename)
  626.   "Return a version of FILENAME shortened using `directory-abbrev-alist'.
  627. This also substitutes \"~\" for the user's home directory.
  628. Type \\[describe-variable] directory-abbrev-alist RET for more information."
  629.   ;; Get rid of the prefixes added by the automounter.
  630.   (if (and automount-dir-prefix
  631.        (string-match automount-dir-prefix filename)
  632.        (file-exists-p (file-name-directory
  633.                (substring filename (1- (match-end 0))))))
  634.       (setq filename (substring filename (1- (match-end 0)))))
  635.   (let ((tail directory-abbrev-alist))
  636.     ;; If any elt of directory-abbrev-alist matches this name,
  637.     ;; abbreviate accordingly.
  638.     (while tail
  639.       (if (string-match (car (car tail)) filename)
  640.       (setq filename
  641.         (concat (cdr (car tail)) (substring filename (match-end 0)))))
  642.       (setq tail (cdr tail)))
  643.     ;; Compute and save the abbreviated homedir name.
  644.     ;; We defer computing this until the first time it's needed, to
  645.     ;; give time for directory-abbrev-alist to be set properly.
  646.     ;; We include a slash at the end, to avoid spurious matches
  647.     ;; such as `/usr/foobar' when the home dir is `/usr/foo'.
  648.     (or abbreviated-home-dir
  649.     (setq abbreviated-home-dir
  650.           (let ((abbreviated-home-dir "$foo"))
  651.         (concat "^" (abbreviate-file-name (expand-file-name "~"))
  652.             "\\(/\\|$\\)"))))
  653.  
  654.     ;; If FILENAME starts with the abbreviated homedir,
  655.     ;; make it start with `~' instead.
  656.     (if (and (string-match abbreviated-home-dir filename)
  657.          ;; If the home dir is just /, don't change it.
  658.          (not (and (= (match-end 0) 1)
  659.                (= (aref filename 0) ?/)))
  660.          ;; MS-DOS root directories can come with a drive letter;
  661.          ;; Novell Netware allows drive letters beyond `Z:'.
  662.          (not (and (or (eq system-type 'ms-dos)
  663.                (eq system-type 'windows-nt))
  664.                (save-match-data
  665.              (string-match "^[a-zA-`]:/$" filename)))))
  666.     (setq filename
  667.           (concat "~"
  668.               (substring filename (match-beginning 1) (match-end 1))
  669.               (substring filename (match-end 0)))))
  670.     filename))
  671.  
  672. (defvar find-file-not-true-dirname-list nil
  673.   "*List of logical names for which visiting shouldn't save the true dirname.
  674. On VMS, when you visit a file using a logical name that searches a path,
  675. you may or may not want the visited file name to record the specific
  676. directory where the file was found.  If you *do not* want that, add the logical
  677. name to this list as a string.")
  678.  
  679. (defun find-buffer-visiting (filename)
  680.   "Return the buffer visiting file FILENAME (a string).
  681. This is like `get-file-buffer', except that it checks for any buffer
  682. visiting the same file, possibly under a different name.
  683. If there is no such live buffer, return nil."
  684.   (let ((buf (get-file-buffer filename))
  685.     (truename (abbreviate-file-name (file-truename filename))))
  686.     (or buf
  687.     (let ((list (buffer-list)) found)
  688.       (while (and (not found) list)
  689.         (save-excursion
  690.           (set-buffer (car list))
  691.           (if (and buffer-file-name
  692.                (string= buffer-file-truename truename))
  693.           (setq found (car list))))
  694.         (setq list (cdr list)))
  695.       found)
  696.     (let ((number (nthcdr 10 (file-attributes truename)))
  697.           (list (buffer-list)) found)
  698.       (and buffer-file-numbers-unique
  699.            number
  700.            (while (and (not found) list)
  701.          (save-excursion
  702.            (set-buffer (car list))
  703.            (if (and buffer-file-name
  704.                 (equal buffer-file-number number)
  705.                 ;; Verify this buffer's file number
  706.                 ;; still belongs to its file.
  707.                 (file-exists-p buffer-file-name)
  708.                 (equal (nthcdr 10 (file-attributes buffer-file-name))
  709.                    number))
  710.                (setq found (car list))))
  711.          (setq list (cdr list))))
  712.       found))))
  713.  
  714. (defun insert-file-contents-literally (filename &optional visit beg end replace)
  715.   "Like `insert-file-contents', q.v., but only reads in the file.
  716. A buffer may be modified in several ways after reading into the buffer due
  717. to advanced Emacs features, such as file-name-handlers, format decoding,
  718. find-file-hooks, etc.
  719.   This function ensures that none of these modifications will take place."
  720.   (let ((file-name-handler-alist nil)
  721.     (format-alist nil)
  722.     (after-insert-file-functions nil)
  723.     (find-buffer-file-type-function
  724.      (if (fboundp 'find-buffer-file-type)
  725.          (symbol-function 'find-buffer-file-type)
  726.        nil)))
  727.     (unwind-protect
  728.     (progn
  729.       (fset 'find-buffer-file-type (lambda (filename) t))
  730.       (insert-file-contents filename visit beg end replace))
  731.       (if find-buffer-file-type-function
  732.       (fset 'find-buffer-file-type find-buffer-file-type-function)
  733.     (fmakunbound 'find-buffer-file-type)))))
  734.  
  735. (defun find-file-noselect (filename &optional nowarn rawfile)
  736.   "Read file FILENAME into a buffer and return the buffer.
  737. If a buffer exists visiting FILENAME, return that one, but
  738. verify that the file has not changed since visited or saved.
  739. The buffer is not selected, just returned to the caller."
  740.   (setq filename
  741.     (abbreviate-file-name
  742.      (expand-file-name filename)))
  743.   (if (file-directory-p filename)
  744.       (if find-file-run-dired
  745.       (dired-noselect (if find-file-visit-truename
  746.                   (abbreviate-file-name (file-truename filename))
  747.                 filename))
  748.     (error "%s is a directory" filename))
  749.     (let* ((buf (get-file-buffer filename))
  750.        (truename (abbreviate-file-name (file-truename filename)))
  751.        (number (nthcdr 10 (file-attributes truename)))
  752.        ;; Find any buffer for a file which has same truename.
  753.        (other (and (not buf) (find-buffer-visiting filename)))
  754.        error)
  755.       ;; Let user know if there is a buffer with the same truename.
  756.       (if other
  757.       (progn
  758.         (or nowarn
  759.         (string-equal filename (buffer-file-name other))
  760.         (message "%s and %s are the same file"
  761.              filename (buffer-file-name other)))
  762.         ;; Optionally also find that buffer.
  763.         (if (or find-file-existing-other-name find-file-visit-truename)
  764.         (setq buf other))))
  765.       (if buf
  766.       (or nowarn
  767.           (verify-visited-file-modtime buf)
  768.           (cond ((not (file-exists-p filename))
  769.              (error "File %s no longer exists!" filename))
  770.             ((yes-or-no-p
  771.               (if (string= (file-name-nondirectory filename)
  772.                    (buffer-name buf))
  773.               (format
  774.                (if (buffer-modified-p buf)
  775.     "File %s changed on disk.  Discard your edits? "
  776.     "File %s changed on disk.  Reread from disk? ")
  777.                (file-name-nondirectory filename))
  778.             (format
  779.              (if (buffer-modified-p buf)
  780.       "File %s changed on disk.  Discard your edits in %s? "
  781.       "File %s changed on disk.  Reread from disk into %s? ")
  782.              (file-name-nondirectory filename)
  783.              (buffer-name buf))))
  784.              (save-excursion
  785.                (set-buffer buf)
  786.                (revert-buffer t t)))))
  787.     (save-excursion
  788. ;;; The truename stuff makes this obsolete.
  789. ;;;      (let* ((link-name (car (file-attributes filename)))
  790. ;;;         (linked-buf (and (stringp link-name)
  791. ;;;                  (get-file-buffer link-name))))
  792. ;;;        (if (bufferp linked-buf)
  793. ;;;        (message "Symbolic link to file in buffer %s"
  794. ;;;             (buffer-name linked-buf))))
  795.       (setq buf (create-file-buffer filename))
  796.       (set-buffer-major-mode buf)
  797.       (set-buffer buf)
  798.       (erase-buffer)
  799.       (if rawfile
  800.           (condition-case ()
  801.           (insert-file-contents-literally filename t)
  802.         (file-error
  803.          ;; Unconditionally set error
  804.          (setq error t)))
  805.         (condition-case ()
  806.         (insert-file-contents filename t)
  807.           (file-error
  808.            ;; Run find-file-not-found-hooks until one returns non-nil.
  809.            (or (run-hook-with-args-until-success 'find-file-not-found-hooks)
  810.            ;; If they fail too, set error.
  811.            (setq error t)))))
  812.       ;; Find the file's truename, and maybe use that as visited name.
  813.       (setq buffer-file-truename truename)
  814.       (setq buffer-file-number number)
  815.       ;; On VMS, we may want to remember which directory in a search list
  816.       ;; the file was found in.
  817.       (and (eq system-type 'vax-vms)
  818.            (let (logical)
  819.          (if (string-match ":" (file-name-directory filename))
  820.              (setq logical (substring (file-name-directory filename)
  821.                           0 (match-beginning 0))))
  822.          (not (member logical find-file-not-true-dirname-list)))
  823.            (setq buffer-file-name buffer-file-truename))
  824.       (if find-file-visit-truename
  825.           (setq buffer-file-name
  826.             (setq filename
  827.               (expand-file-name buffer-file-truename))))
  828.       ;; Set buffer's default directory to that of the file.
  829.       (setq default-directory (file-name-directory filename))
  830.       ;; Turn off backup files for certain file names.  Since
  831.       ;; this is a permanent local, the major mode won't eliminate it.
  832.       (and (not (funcall backup-enable-predicate buffer-file-name))
  833.            (progn
  834.          (make-local-variable 'backup-inhibited)
  835.          (setq backup-inhibited t)))
  836.       (if rawfile
  837.           nil
  838.         (after-find-file error (not nowarn))
  839.         (setq buf (current-buffer)))))
  840.       buf)))
  841.  
  842. (defvar after-find-file-from-revert-buffer nil)
  843.  
  844. (defun after-find-file (&optional error warn noauto
  845.                   after-find-file-from-revert-buffer
  846.                   nomodes)
  847.   "Called after finding a file and by the default revert function.
  848. Sets buffer mode, parses local variables.
  849. Optional args ERROR, WARN, and NOAUTO: ERROR non-nil means there was an
  850. error in reading the file.  WARN non-nil means warn if there
  851. exists an auto-save file more recent than the visited file.
  852. NOAUTO means don't mess with auto-save mode.
  853. Fourth arg AFTER-FIND-FILE-FROM-REVERT-BUFFER non-nil
  854.  means this call was from `revert-buffer'.
  855. Fifth arg NOMODES non-nil means don't alter the file's modes.
  856. Finishes by calling the functions in `find-file-hooks'
  857. unless NOMODES is non-nil."
  858.   (setq buffer-read-only (not (file-writable-p buffer-file-name)))
  859.   (if noninteractive
  860.       nil
  861.     (let* (not-serious
  862.        (msg
  863.         (cond ((and error (file-attributes buffer-file-name))
  864.            (setq buffer-read-only t)
  865.            "File exists, but cannot be read.")
  866.           ((not buffer-read-only)
  867.            (if (and warn
  868.                 (file-newer-than-file-p (make-auto-save-file-name)
  869.                             buffer-file-name))
  870.                (format "%s has auto save data; consider M-x recover-file"
  871.                    (file-name-nondirectory buffer-file-name))
  872.              (setq not-serious t)
  873.              (if error "(New file)" nil)))
  874.           ((not error)
  875.            (setq not-serious t)
  876.            "Note: file is write protected")
  877.           ((file-attributes (directory-file-name default-directory))
  878.            "File not found and directory write-protected")
  879.           ((file-exists-p (file-name-directory buffer-file-name))
  880.            (setq buffer-read-only nil))
  881.           (t
  882.            (setq buffer-read-only nil)
  883.            (if (file-exists-p (file-name-directory (directory-file-name (file-name-directory buffer-file-name))))
  884.                "Use M-x make-dir RET RET to create the directory"
  885.              "Use C-u M-x make-dir RET RET to create directory and its parents")))))
  886.       (if msg
  887.       (progn
  888.         (message msg)
  889.         (or not-serious (sit-for 1 nil t)))))
  890.     (if (and auto-save-default (not noauto))
  891.     (auto-save-mode t)))
  892.   (if nomodes
  893.       nil
  894.     (normal-mode t)
  895.     (run-hooks 'find-file-hooks)))
  896.  
  897. (defun normal-mode (&optional find-file)
  898.   "Choose the major mode for this buffer automatically.
  899. Also sets up any specified local variables of the file.
  900. Uses the visited file name, the -*- line, and the local variables spec.
  901.  
  902. This function is called automatically from `find-file'.  In that case,
  903. we may set up specified local variables depending on the value of
  904. `enable-local-variables': if it is t, we do; if it is nil, we don't;
  905. otherwise, we query.  `enable-local-variables' is ignored if you
  906. run `normal-mode' explicitly."
  907.   (interactive)
  908.   (or find-file (funcall (or default-major-mode 'fundamental-mode)))
  909.   (condition-case err
  910.       (set-auto-mode)
  911.     (error (message "File mode specification error: %s"
  912.             (prin1-to-string err))))
  913.   (condition-case err
  914.       (let ((enable-local-variables (or (not find-file)
  915.                     enable-local-variables)))
  916.     (hack-local-variables))
  917.     (error (message "File local-variables error: %s"
  918.             (prin1-to-string err)))))
  919.  
  920. (defvar auto-mode-alist
  921.   '(("\\.te?xt\\'" . text-mode)
  922.     ("\\.c\\'" . c-mode)
  923.     ("\\.h\\'" . c-mode)
  924.     ("\\.tex\\'" . tex-mode)
  925.     ("\\.ltx\\'" . latex-mode)
  926.     ("\\.el\\'" . emacs-lisp-mode)
  927.     ("\\.mm\\'" . nroff-mode)
  928.     ("\\.me\\'" . nroff-mode)
  929.     ("\\.ms\\'" . nroff-mode)
  930.     ("\\.man\\'" . nroff-mode)
  931.     ("\\.scm\\'" . scheme-mode)
  932.     ("\\.l\\'" . lisp-mode)
  933.     ("\\.lisp\\'" . lisp-mode)
  934.     ("\\.f\\'" . fortran-mode)
  935.     ("\\.F\\'" . fortran-mode)
  936.     ("\\.for\\'" . fortran-mode)
  937.     ("\\.p\\'" . pascal-mode)
  938.     ("\\.pas\\'" . pascal-mode)
  939.     ("\\.mss\\'" . scribe-mode)
  940.     ("\\.ad[abs]\\'" . ada-mode)
  941.     ("\\.icn\\'" . icon-mode)
  942.     ("\\.pl\\'" . perl-mode)
  943.     ("\\.pm\\'" . perl-mode)
  944.     ("\\.cc\\'" . c++-mode)
  945.     ("\\.hh\\'" . c++-mode)
  946.     ("\\.C\\'" . c++-mode)
  947.     ("\\.H\\'" . c++-mode)
  948.     ("\\.cpp\\'" . c++-mode)
  949.     ("\\.cxx\\'" . c++-mode)
  950.     ("\\.hxx\\'" . c++-mode)
  951.     ("\\.c\\+\\+\\'" . c++-mode)
  952.     ("\\.h\\+\\+\\'" . c++-mode)
  953.     ("\\.java\\'" . java-mode)
  954.     ("\\.mk\\'" . makefile-mode)
  955.     ("\\(M\\|m\\|GNUm\\)akefile\\(.in\\)?\\'" . makefile-mode)
  956. ;;; Less common extensions come here
  957. ;;; so more common ones above are found faster.
  958.     ("\\.texinfo\\'" . texinfo-mode)
  959.     ("\\.te?xi\\'" . texinfo-mode)
  960.     ("\\.s\\'" . asm-mode)
  961.     ("\\.S\\'" . asm-mode)
  962.     ("\\.asm\\'" . asm-mode)
  963.     ("ChangeLog\\'" . change-log-mode)
  964.     ("change.log\\'" . change-log-mode)
  965.     ("changelo\\'" . change-log-mode)
  966.     ("ChangeLog.[0-9]+\\'" . change-log-mode)
  967.     ("\\$CHANGE_LOG\\$\\.TXT" . change-log-mode)
  968.     ("\\.scm\\.[0-9]*\\'" . scheme-mode)
  969.     ("\\.[ck]?sh\\'\\|\\.shar\\'\\|/\\.z?profile\\'" . sh-mode)
  970.     ("/\\.\\(bash_profile\\|z?login\\|bash_login\\|z?logout\\)\\'" . sh-mode)
  971.     ("/\\.\\(bash_logout\\|[kz]shrc\\|bashrc\\|t?cshrc\\|esrc\\)\\'" . sh-mode)
  972.     ("/\\.\\([kz]shenv\\|xinitrc\\|startxrc\\|xsession\\)\\'" . sh-mode)
  973. ;;; The following should come after the ChangeLog pattern
  974. ;;; for the sake of ChangeLog.1, etc.
  975. ;;; and after the .scm.[0-9] pattern too.
  976.     ("\\.[12345678]\\'" . nroff-mode)
  977.     ("\\.TeX\\'" . tex-mode)
  978.     ("\\.sty\\'" . latex-mode)
  979.     ("\\.cls\\'" . latex-mode)        ;LaTeX 2e class
  980.     ("\\.bbl\\'" . latex-mode)
  981.     ("\\.bib\\'" . bibtex-mode)
  982.     ("\\.article\\'" . text-mode)
  983.     ("\\.letter\\'" . text-mode)
  984.     ("\\.tcl\\'" . tcl-mode)
  985.     ("\\.exp\\'" . tcl-mode)
  986.     ("\\.itcl\\'" . tcl-mode)
  987.     ("\\.itk\\'" . tcl-mode)
  988.     ("\\.f90\\'" . f90-mode)
  989.     ("\\.lsp\\'" . lisp-mode)
  990.     ("\\.awk\\'" . awk-mode)
  991.     ("\\.prolog\\'" . prolog-mode)
  992.     ("\\.tar\\'" . tar-mode)
  993.     ("\\.\\(arc\\|zip\\|lzh\\|zoo\\)\\'" . archive-mode)
  994.     ("\\.\\(ARC\\|ZIP\\|LZH\\|ZOO\\)\\'" . archive-mode)
  995.     ;; Mailer puts message to be edited in
  996.     ;; /tmp/Re.... or Message
  997.     ("\\`/tmp/Re" . text-mode)
  998.     ("/Message[0-9]*\\'" . text-mode)
  999.     ("/drafts/[0-9]+\\'" . mh-letter-mode)
  1000.     ;; some news reader is reported to use this
  1001.     ("\\`/tmp/fol/" . text-mode)
  1002.     ("\\.y\\'" . c-mode)
  1003.     ("\\.lex\\'" . c-mode)
  1004.     ("\\.oak\\'" . scheme-mode)
  1005.     ("\\.sgml?\\'" . sgml-mode)
  1006.     ("\\.dtd\\'" . sgml-mode)
  1007.     ("\\.s?html?\\'" . html-mode)
  1008.     ;; .emacs following a directory delimiter
  1009.     ;; in either Unix or VMS syntax.
  1010.     ("[]>:/]\\..*emacs\\'" . emacs-lisp-mode)
  1011.     ;; _emacs following a directory delimiter
  1012.     ;; in MsDos syntax
  1013.     ("[:/]_emacs\\'" . emacs-lisp-mode)
  1014.     ("\\.ml\\'" . lisp-mode))
  1015.   "\
  1016. Alist of filename patterns vs corresponding major mode functions.
  1017. Each element looks like (REGEXP . FUNCTION) or (REGEXP FUNCTION NON-NIL).
  1018. \(NON-NIL stands for anything that is not nil; the value does not matter.)
  1019. Visiting a file whose name matches REGEXP specifies FUNCTION as the
  1020. mode function to use.  FUNCTION will be called, unless it is nil.
  1021.  
  1022. If the element has the form (REGEXP FUNCTION NON-NIL), then after
  1023. calling FUNCTION (if it's not nil), we delete the suffix that matched
  1024. REGEXP and search the list again for another match.")
  1025.  
  1026. (defconst interpreter-mode-alist
  1027.   '(("perl" . perl-mode)
  1028.     ("perl5" . perl-mode)
  1029.     ("wish" . tcl-mode)
  1030.     ("wishx" . tcl-mode)
  1031.     ("tcl" . tcl-mode)
  1032.     ("tclsh" . tcl-mode)
  1033.     ("awk" . awk-mode)
  1034.     ("mawk" . awk-mode)
  1035.     ("nawk" . awk-mode)
  1036.     ("gawk" . awk-mode)
  1037.     ("scm" . scheme-mode)
  1038.     ("ash" . sh-mode)
  1039.     ("bash" . sh-mode)
  1040.     ("csh" . sh-mode)
  1041.     ("dtksh" . sh-mode)
  1042.     ("es" . sh-mode)
  1043.     ("itcsh" . sh-mode)
  1044.     ("jsh" . sh-mode)
  1045.     ("ksh" . sh-mode)
  1046.     ("oash" . sh-mode)
  1047.     ("pdksh" . sh-mode)
  1048.     ("rc" . sh-mode)
  1049.     ("sh" . sh-mode)
  1050.     ("sh5" . sh-mode)
  1051.     ("tcsh" . sh-mode)
  1052.     ("wksh" . sh-mode)
  1053.     ("wsh" . sh-mode)
  1054.     ("zsh" . sh-mode)
  1055.     ("tail" . text-mode)
  1056.     ("more" . text-mode)
  1057.     ("less" . text-mode)
  1058.     ("pg" . text-mode))
  1059.   "Alist mapping interpreter names to major modes.
  1060. This alist applies to files whose first line starts with `#!'.
  1061. Each element looks like (INTERPRETER . MODE).
  1062. The car of each element is compared with
  1063. the name of the interpreter specified in the first line.
  1064. If it matches, mode MODE is selected.")
  1065.  
  1066. (defconst inhibit-first-line-modes-regexps '("\\.tar\\'")
  1067.   "List of regexps; if one matches a file name, don't look for `-*-'.")
  1068.  
  1069. (defconst inhibit-first-line-modes-suffixes nil
  1070.   "List of regexps for what to ignore, for `inhibit-first-line-modes-regexps'.
  1071. When checking `inhibit-first-line-modes-regexps', we first discard
  1072. from the end of the file name anything that matches one of these regexps.")
  1073.  
  1074. (defvar user-init-file
  1075.   "" ; set by command-line
  1076.   "File name including directory of user's initialization file.")
  1077.  
  1078. (defun set-auto-mode ()
  1079.   "Select major mode appropriate for current buffer.
  1080. This checks for a -*- mode tag in the buffer's text,
  1081. compares the filename against the entries in `auto-mode-alist',
  1082. or checks the interpreter that runs this file against
  1083. `interpreter-mode-alist'.
  1084.  
  1085. It does not check for the `mode:' local variable in the
  1086. Local Variables section of the file; for that, use `hack-local-variables'.
  1087.  
  1088. If `enable-local-variables' is nil, this function does not check for a
  1089. -*- mode tag."
  1090.   ;; Look for -*-MODENAME-*- or -*- ... mode: MODENAME; ... -*-
  1091.   (let (beg end done modes)
  1092.     (save-excursion
  1093.       (goto-char (point-min))
  1094.       (skip-chars-forward " \t\n")
  1095.       (and enable-local-variables
  1096.        ;; Don't look for -*- if this file name matches any
  1097.        ;; of the regexps in inhibit-first-line-modes-regexps.
  1098.        (let ((temp inhibit-first-line-modes-regexps)
  1099.          (name (if buffer-file-name
  1100.                (file-name-sans-versions buffer-file-name)
  1101.              (buffer-name))))
  1102.          (while (let ((sufs inhibit-first-line-modes-suffixes))
  1103.               (while (and sufs (not (string-match (car sufs) name)))
  1104.             (setq sufs (cdr sufs)))
  1105.               sufs)
  1106.            (setq name (substring name 0 (match-beginning 0))))
  1107.          (while (and temp
  1108.              (not (string-match (car temp) name)))
  1109.            (setq temp (cdr temp)))
  1110.          (not temp))
  1111.        (search-forward "-*-" (save-excursion
  1112.                    ;; If the file begins with "#!"
  1113.                    ;; (exec interpreter magic), look
  1114.                    ;; for mode frobs in the first two
  1115.                    ;; lines.  You cannot necessarily
  1116.                    ;; put them in the first line of
  1117.                    ;; such a file without screwing up
  1118.                    ;; the interpreter invocation.
  1119.                    (end-of-line (and (looking-at "^#!") 2))
  1120.                    (point)) t)
  1121.        (progn
  1122.          (skip-chars-forward " \t")
  1123.          (setq beg (point))
  1124.          (search-forward "-*-"
  1125.                  (save-excursion (end-of-line) (point))
  1126.                  t))
  1127.        (progn
  1128.          (forward-char -3)
  1129.          (skip-chars-backward " \t")
  1130.          (setq end (point))
  1131.          (goto-char beg)
  1132.          (if (save-excursion (search-forward ":" end t))
  1133.          ;; Find all specifications for the `mode:' variable
  1134.          ;; and execute them left to right.
  1135.          (while (let ((case-fold-search t))
  1136.               (or (and (looking-at "mode:")
  1137.                    (goto-char (match-end 0)))
  1138.                   (re-search-forward "[ \t;]mode:" end t)))
  1139.            (skip-chars-forward " \t")
  1140.            (setq beg (point))
  1141.            (if (search-forward ";" end t)
  1142.                (forward-char -1)
  1143.              (goto-char end))
  1144.            (skip-chars-backward " \t")
  1145.            (setq modes (cons (intern (concat (downcase (buffer-substring beg (point))) "-mode"))
  1146.                      modes)))
  1147.            ;; Simple -*-MODE-*- case.
  1148.            (setq modes (cons (intern (concat (downcase (buffer-substring beg end))
  1149.                          "-mode"))
  1150.                  modes))))))
  1151.     ;; If we found modes to use, invoke them now,
  1152.     ;; outside the save-excursion.
  1153.     (if modes
  1154.     (progn (mapcar 'funcall (nreverse modes))
  1155.            (setq done t)))
  1156.     ;; If we didn't find a mode from a -*- line, try using the file name.
  1157.     (if (and (not done) buffer-file-name)
  1158.     (let ((name buffer-file-name)
  1159.           (keep-going t))
  1160.       ;; Remove backup-suffixes from file name.
  1161.       (setq name (file-name-sans-versions name))
  1162.       (while keep-going
  1163.         (setq keep-going nil)
  1164.         (let ((alist auto-mode-alist)
  1165.           (mode nil))
  1166.           ;; Find first matching alist entry.
  1167.           (let ((case-fold-search
  1168.              (memq system-type '(vax-vms windows-nt))))
  1169.         (while (and (not mode) alist)
  1170.           (if (string-match (car (car alist)) name)
  1171.               (if (and (consp (cdr (car alist)))
  1172.                    (nth 2 (car alist)))
  1173.               (progn
  1174.                 (setq mode (car (cdr (car alist)))
  1175.                   name (substring name 0 (match-beginning 0))
  1176.                   keep-going t))
  1177.             (setq mode (cdr (car alist))
  1178.                   keep-going nil)))
  1179.           (setq alist (cdr alist))))
  1180.           (if mode
  1181.           (funcall mode)
  1182.         ;; If we can't deduce a mode from the file name,
  1183.         ;; look for an interpreter specified in the first line.
  1184.         ;; As a special case, allow for things like "#!/bin/env perl",
  1185.         ;; which finds the interpreter anywhere in $PATH.
  1186.         (let ((interpreter
  1187.                (save-excursion
  1188.              (goto-char (point-min))
  1189.              (if (looking-at "#![ \t]?\\([^ \t\n]*/bin/env[ \t]\\)?\\([^ \t\n]+\\)")
  1190.                  (buffer-substring (match-beginning 2)
  1191.                            (match-end 2))
  1192.                "")))
  1193.               elt)
  1194.           ;; Map interpreter name to a mode.
  1195.           (setq elt (assoc (file-name-nondirectory interpreter)
  1196.                    interpreter-mode-alist))
  1197.           (if elt
  1198.               (funcall (cdr elt)))))))))))
  1199.  
  1200. (defun hack-local-variables-prop-line ()
  1201.   ;; Set local variables specified in the -*- line.
  1202.   ;; Ignore any specification for `mode:';
  1203.   ;; set-auto-mode should already have handled that.
  1204.   (save-excursion
  1205.     (goto-char (point-min))
  1206.     (let ((result nil)
  1207.       (end (save-excursion (end-of-line (and (looking-at "^#!") 2)) (point))))
  1208.       ;; Parse the -*- line into the `result' alist.
  1209.       (cond ((not (search-forward "-*-" end t))
  1210.          ;; doesn't have one.
  1211.          nil)
  1212.         ((looking-at "[ \t]*\\([^ \t\n\r:;]+\\)\\([ \t]*-\\*-\\)")
  1213.          ;; Simple form: "-*- MODENAME -*-".  Already handled.
  1214.          nil)
  1215.         (t
  1216.          ;; Hairy form: '-*-' [ <variable> ':' <value> ';' ]* '-*-'
  1217.          ;; (last ";" is optional).
  1218.          (save-excursion
  1219.            (if (search-forward "-*-" end t)
  1220.            (setq end (- (point) 3))
  1221.          (error "-*- not terminated before end of line")))
  1222.          (while (< (point) end)
  1223.            (or (looking-at "[ \t]*\\([^ \t\n:]+\\)[ \t]*:[ \t]*")
  1224.            (error "malformed -*- line"))
  1225.            (goto-char (match-end 0))
  1226.            ;; There used to be a downcase here,
  1227.            ;; but the manual didn't say so,
  1228.            ;; and people want to set var names that aren't all lc.
  1229.            (let ((key (intern (buffer-substring
  1230.                    (match-beginning 1)
  1231.                    (match-end 1))))
  1232.              (val (save-restriction
  1233.                 (narrow-to-region (point) end)
  1234.                 (read (current-buffer)))))
  1235.          (or (eq key 'mode)
  1236.              (setq result (cons (cons key val) result)))
  1237.          (skip-chars-forward " \t;")))
  1238.          (setq result (nreverse result))))
  1239.  
  1240.       (if (and result
  1241.            (or (eq enable-local-variables t)
  1242.            (and enable-local-variables
  1243.             (save-window-excursion
  1244.               (condition-case nil
  1245.                   (switch-to-buffer (current-buffer))
  1246.                 (error
  1247.                  ;; If we fail to switch in the selected window,
  1248.                  ;; it is probably a minibuffer.
  1249.                  ;; So try another window.
  1250.                  (condition-case nil
  1251.                  (switch-to-buffer-other-window (current-buffer))
  1252.                    (error
  1253.                 (switch-to-buffer-other-frame (current-buffer))))))
  1254.               (y-or-n-p (format "Set local variables as specified in -*- line of %s? "
  1255.                         (file-name-nondirectory buffer-file-name)))))))
  1256.       (let ((enable-local-eval enable-local-eval))
  1257.         (while result
  1258.           (hack-one-local-variable (car (car result)) (cdr (car result)))
  1259.           (setq result (cdr result))))))))
  1260.  
  1261. (defvar hack-local-variables-hook nil
  1262.   "Normal hook run after processing a file's local variables specs.
  1263. Major modes can use this to examine user-specified local variables
  1264. in order to initialize other data structure based on them.")
  1265.  
  1266. (defun hack-local-variables ()
  1267.   "Parse and put into effect this buffer's local variables spec."
  1268.   (hack-local-variables-prop-line)
  1269.   ;; Look for "Local variables:" line in last page.
  1270.   (save-excursion
  1271.     (goto-char (point-max))
  1272.     (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move)
  1273.     (if (let ((case-fold-search t))
  1274.       (and (search-forward "Local Variables:" nil t)
  1275.            (or (eq enable-local-variables t)
  1276.            (and enable-local-variables
  1277.             (save-window-excursion
  1278.               (switch-to-buffer (current-buffer))
  1279.               (save-excursion
  1280.                 (beginning-of-line)
  1281.                 (set-window-start (selected-window) (point)))
  1282.               (y-or-n-p (format "Set local variables as specified at end of %s? "
  1283.                          (if buffer-file-name
  1284.                          (file-name-nondirectory
  1285.                           buffer-file-name)
  1286.                            (concat "buffer "
  1287.                                (buffer-name))))))))))
  1288.     (let ((continue t)
  1289.           prefix prefixlen suffix beg
  1290.           (enable-local-eval enable-local-eval))
  1291.       ;; The prefix is what comes before "local variables:" in its line.
  1292.       ;; The suffix is what comes after "local variables:" in its line.
  1293.       (skip-chars-forward " \t")
  1294.       (or (eolp)
  1295.           (setq suffix (buffer-substring (point)
  1296.                          (progn (end-of-line) (point)))))
  1297.       (goto-char (match-beginning 0))
  1298.       (or (bolp)
  1299.           (setq prefix
  1300.             (buffer-substring (point)
  1301.                       (progn (beginning-of-line) (point)))))
  1302.  
  1303.       (if prefix (setq prefixlen (length prefix)
  1304.                prefix (regexp-quote prefix)))
  1305.       (if suffix (setq suffix (concat (regexp-quote suffix) "$")))
  1306.       (while continue
  1307.         ;; Look at next local variable spec.
  1308.         (if selective-display (re-search-forward "[\n\C-m]")
  1309.           (forward-line 1))
  1310.         ;; Skip the prefix, if any.
  1311.         (if prefix
  1312.         (if (looking-at prefix)
  1313.             (forward-char prefixlen)
  1314.           (error "Local variables entry is missing the prefix")))
  1315.         ;; Find the variable name; strip whitespace.
  1316.         (skip-chars-forward " \t")
  1317.         (setq beg (point))
  1318.         (skip-chars-forward "^:\n")
  1319.         (if (eolp) (error "Missing colon in local variables entry"))
  1320.         (skip-chars-backward " \t")
  1321.         (let* ((str (buffer-substring beg (point)))
  1322.            (var (read str))
  1323.           val)
  1324.           ;; Setting variable named "end" means end of list.
  1325.           (if (string-equal (downcase str) "end")
  1326.           (setq continue nil)
  1327.         ;; Otherwise read the variable value.
  1328.         (skip-chars-forward "^:")
  1329.         (forward-char 1)
  1330.         (setq val (read (current-buffer)))
  1331.         (skip-chars-backward "\n")
  1332.         (skip-chars-forward " \t")
  1333.         (or (if suffix (looking-at suffix) (eolp))
  1334.             (error "Local variables entry is terminated incorrectly"))
  1335.         ;; Set the variable.  "Variables" mode and eval are funny.
  1336.         (hack-one-local-variable var val)))))))
  1337.   (run-hooks 'hack-local-variables-hook))
  1338.  
  1339. (defconst ignored-local-variables
  1340.   '(enable-local-eval)
  1341.   "Variables to be ignored in a file's local variable spec.")
  1342.  
  1343. ;; Get confirmation before setting these variables as locals in a file.
  1344. (put 'debugger 'risky-local-variable t)
  1345. (put 'enable-local-eval 'risky-local-variable t)
  1346. (put 'ignored-local-variables 'risky-local-variable t)
  1347. (put 'eval 'risky-local-variable t)
  1348. (put 'file-name-handler-alist 'risky-local-variable t)
  1349. (put 'minor-mode-map-alist 'risky-local-variable t)
  1350. (put 'after-load-alist 'risky-local-variable t)
  1351. (put 'buffer-file-name 'risky-local-variable t)
  1352. (put 'buffer-auto-save-file-name 'risky-local-variable t)
  1353. (put 'buffer-file-truename 'risky-local-variable t)
  1354. (put 'exec-path 'risky-local-variable t)
  1355. (put 'load-path 'risky-local-variable t)
  1356. (put 'exec-directory 'risky-local-variable t)
  1357. (put 'process-environment 'risky-local-variable t)
  1358. (put 'dabbrev-case-fold-search 'risky-local-variable t)
  1359. (put 'dabbrev-case-replace 'risky-local-variable t)
  1360. ;; Don't wait for outline.el to be loaded, for the sake of outline-minor-mode.
  1361. (put 'outline-level 'risky-local-variable t)
  1362. (put 'rmail-output-file-alist 'risky-local-variable t)
  1363.  
  1364. ;; This one is safe because the user gets to check it before it is used.
  1365. (put 'compile-command 'safe-local-variable t)
  1366.  
  1367. (defun hack-one-local-variable-quotep (exp)
  1368.   (and (consp exp) (eq (car exp) 'quote) (consp (cdr exp))))
  1369.  
  1370. ;; "Set" one variable in a local variables spec.
  1371. ;; A few variable names are treated specially.
  1372. (defun hack-one-local-variable (var val)
  1373.   (cond ((eq var 'mode)
  1374.      (funcall (intern (concat (downcase (symbol-name val))
  1375.                   "-mode"))))
  1376.     ((memq var ignored-local-variables)
  1377.      nil)
  1378.     ;; "Setting" eval means either eval it or do nothing.
  1379.     ;; Likewise for setting hook variables.
  1380.     ((or (get var 'risky-local-variable)
  1381.          (and
  1382.           (string-match "-hooks?$\\|-functions?$\\|-forms?$\\|-program$\\|-command$"
  1383.                 (symbol-name var))
  1384.           (not (get var 'safe-local-variable))))
  1385.      ;; Permit evalling a put of a harmless property.
  1386.      ;; if the args do nothing tricky.
  1387.      (if (or (and (eq var 'eval)
  1388.               (consp val)
  1389.               (eq (car val) 'put)
  1390.               (hack-one-local-variable-quotep (nth 1 val))
  1391.               (hack-one-local-variable-quotep (nth 2 val))
  1392.               ;; Only allow safe values of lisp-indent-hook;
  1393.               ;; not functions.
  1394.               (or (numberp (nth 3 val))
  1395.               (equal (nth 3 val) ''defun))
  1396.               (memq (nth 1 (nth 2 val))
  1397.                 '(lisp-indent-hook)))
  1398.          ;; Permit eval if not root and user says ok.
  1399.          (and (not (zerop (user-uid)))
  1400.               (or (eq enable-local-eval t)
  1401.               (and enable-local-eval
  1402.                    (save-window-excursion
  1403.                  (switch-to-buffer (current-buffer))
  1404.                  (save-excursion
  1405.                    (beginning-of-line)
  1406.                    (set-window-start (selected-window) (point)))
  1407.                  (setq enable-local-eval
  1408.                        (y-or-n-p (format "Process `eval' or hook local variables in file %s? "
  1409.                              (file-name-nondirectory buffer-file-name)))))))))
  1410.          (if (eq var 'eval)
  1411.          (save-excursion (eval val))
  1412.            (make-local-variable var)
  1413.            (set var val))
  1414.        (message "Ignoring `eval:' in file's local variables")))
  1415.     ;; Ordinary variable, really set it.
  1416.     (t (make-local-variable var)
  1417.        (set var val))))
  1418.  
  1419.  
  1420. (defun set-visited-file-name (filename &optional no-query)
  1421.   "Change name of file visited in current buffer to FILENAME.
  1422. The next time the buffer is saved it will go in the newly specified file.
  1423. nil or empty string as argument means make buffer not be visiting any file.
  1424. Remember to delete the initial contents of the minibuffer
  1425. if you wish to pass an empty string as the argument.
  1426.  
  1427. The optional second argument NO-QUERY, if non-nil, inhibits asking for
  1428. confirmation in the case where the file FILENAME already exists."
  1429.   (interactive "FSet visited file name: ")
  1430.   (if (buffer-base-buffer)
  1431.       (error "An indirect buffer cannot visit a file"))
  1432.   (let (truename)
  1433.     (if filename
  1434.     (setq filename
  1435.           (if (string-equal filename "")
  1436.           nil
  1437.         (expand-file-name filename))))
  1438.     (if filename
  1439.     (progn
  1440.       (setq truename (file-truename filename))
  1441.       (if find-file-visit-truename
  1442.           (setq filename truename))))
  1443.     (let ((buffer (and filename (find-buffer-visiting filename))))
  1444.       (and buffer (not (eq buffer (current-buffer)))
  1445.        (not no-query)
  1446.        (not (y-or-n-p (message "A buffer is visiting %s; proceed? "
  1447.                    filename)))
  1448.        (error "Aborted")))
  1449.     (or (equal filename buffer-file-name)
  1450.     (progn
  1451.       (and filename (lock-buffer filename))
  1452.       (unlock-buffer)))
  1453.     (setq buffer-file-name filename)
  1454.     (if filename            ; make buffer name reflect filename.
  1455.     (let ((new-name (file-name-nondirectory buffer-file-name)))
  1456.       (if (string= new-name "")
  1457.           (error "Empty file name"))
  1458.       (if (eq system-type 'vax-vms)
  1459.           (setq new-name (downcase new-name)))
  1460.       (setq default-directory (file-name-directory buffer-file-name))
  1461.       (or (string= new-name (buffer-name))
  1462.           (rename-buffer new-name t))))
  1463.     (setq buffer-backed-up nil)
  1464.     (clear-visited-file-modtime)
  1465.     ;; Abbreviate the file names of the buffer.
  1466.     (if truename
  1467.     (progn
  1468.       (setq buffer-file-truename (abbreviate-file-name truename))
  1469.       (if find-file-visit-truename
  1470.           (setq buffer-file-name buffer-file-truename))))
  1471.     (setq buffer-file-number
  1472.       (if filename
  1473.           (nthcdr 10 (file-attributes buffer-file-name))
  1474.           nil)))
  1475.   ;; write-file-hooks is normally used for things like ftp-find-file
  1476.   ;; that visit things that are not local files as if they were files.
  1477.   ;; Changing to visit an ordinary local file instead should flush the hook.
  1478.   (kill-local-variable 'write-file-hooks)
  1479.   (kill-local-variable 'local-write-file-hooks)
  1480.   (kill-local-variable 'revert-buffer-function)
  1481.   (kill-local-variable 'backup-inhibited)
  1482.   ;; If buffer was read-only because of version control,
  1483.   ;; that reason is gone now, so make it writable.
  1484.   (if vc-mode
  1485.       (setq buffer-read-only nil))
  1486.   (kill-local-variable 'vc-mode)
  1487.   ;; Turn off backup files for certain file names.
  1488.   ;; Since this is a permanent local, the major mode won't eliminate it.
  1489.   (and (not (funcall backup-enable-predicate buffer-file-name))
  1490.        (progn
  1491.      (make-local-variable 'backup-inhibited)
  1492.      (setq backup-inhibited t)))
  1493.   (let ((oauto buffer-auto-save-file-name))
  1494.     ;; If auto-save was not already on, turn it on if appropriate.
  1495.     (if (not buffer-auto-save-file-name)
  1496.     (and buffer-file-name auto-save-default
  1497.          (auto-save-mode t))
  1498.       ;; If auto save is on, start using a new name.
  1499.       ;; We deliberately don't rename or delete the old auto save
  1500.       ;; for the old visited file name.  This is because perhaps
  1501.       ;; the user wants to save the new state and then compare with the
  1502.       ;; previous state from the auto save file.
  1503.       (setq buffer-auto-save-file-name
  1504.         (make-auto-save-file-name)))
  1505.     ;; Rename the old auto save file if any.
  1506.     (and oauto buffer-auto-save-file-name
  1507.      (file-exists-p oauto)
  1508.      (rename-file oauto buffer-auto-save-file-name t)))
  1509.   (if buffer-file-name
  1510.       (set-buffer-modified-p t)))
  1511.  
  1512. (defun write-file (filename &optional confirm)
  1513.   "Write current buffer into file FILENAME.
  1514. Makes buffer visit that file, and marks it not modified.
  1515. If the buffer is already visiting a file, you can specify
  1516. a directory name as FILENAME, to write a file of the same
  1517. old name in that directory.
  1518.  
  1519. If optional second arg CONFIRM is non-nil,
  1520. ask for confirmation for overwriting an existing file.
  1521. Interactively, confirmation is required unless you supply a prefix argument."
  1522. ;;  (interactive "FWrite file: ")
  1523.   (interactive
  1524.    (list (if buffer-file-name
  1525.          (read-file-name "Write file: "
  1526.                  nil nil nil nil)
  1527.        (read-file-name "Write file: "
  1528.                    (cdr (assq 'default-directory
  1529.                       (buffer-local-variables)))
  1530.                    nil nil (buffer-name)))
  1531.      (not current-prefix-arg)))
  1532.   (or (null filename) (string-equal filename "")
  1533.       (progn
  1534.     ;; If arg is just a directory,
  1535.     ;; use same file name, but in that directory.
  1536.     (if (and (file-directory-p filename) buffer-file-name)
  1537.         (setq filename (concat (file-name-as-directory filename)
  1538.                    (file-name-nondirectory buffer-file-name))))
  1539.     (and confirm
  1540.          (file-exists-p filename)
  1541.          (or (y-or-n-p (format "File `%s' exists; overwrite? " filename))
  1542.          (error "Canceled")))
  1543.     (set-visited-file-name filename)))
  1544.   (set-buffer-modified-p t)
  1545.   (save-buffer))
  1546.  
  1547. (defun backup-buffer ()
  1548.   "Make a backup of the disk file visited by the current buffer, if appropriate.
  1549. This is normally done before saving the buffer the first time.
  1550. If the value is non-nil, it is the result of `file-modes' on the original
  1551. file; this means that the caller, after saving the buffer, should change
  1552. the modes of the new file to agree with the old modes."
  1553.   (if (and make-backup-files (not backup-inhibited)
  1554.        (not buffer-backed-up)
  1555.        (file-exists-p buffer-file-name)
  1556.        (memq (aref (elt (file-attributes buffer-file-name) 8) 0)
  1557.          '(?- ?l)))
  1558.       (let ((real-file-name buffer-file-name)
  1559.         backup-info backupname targets setmodes)
  1560.     ;; If specified name is a symbolic link, chase it to the target.
  1561.     ;; Thus we make the backups in the directory where the real file is.
  1562.     (setq real-file-name (file-chase-links real-file-name))
  1563.     (setq backup-info (find-backup-file-name real-file-name)
  1564.           backupname (car backup-info)
  1565.           targets (cdr backup-info))
  1566. ;;;     (if (file-directory-p buffer-file-name)
  1567. ;;;         (error "Cannot save buffer in directory %s" buffer-file-name))
  1568.     (if backup-info
  1569.         (condition-case ()
  1570.         (let ((delete-old-versions
  1571.                ;; If have old versions to maybe delete,
  1572.                ;; ask the user to confirm now, before doing anything.
  1573.                ;; But don't actually delete til later.
  1574.                (and targets
  1575.                 (or (eq delete-old-versions t) (eq delete-old-versions nil))
  1576.                 (or delete-old-versions
  1577.                 (y-or-n-p (format "Delete excess backup versions of %s? "
  1578.                           real-file-name))))))
  1579.           ;; Actually write the back up file.
  1580.           (condition-case ()
  1581.               (if (or file-precious-flag
  1582.     ;              (file-symlink-p buffer-file-name)
  1583.                   backup-by-copying
  1584.                   (and backup-by-copying-when-linked
  1585.                    (> (file-nlinks real-file-name) 1))
  1586.                   (and backup-by-copying-when-mismatch
  1587.                    (let ((attr (file-attributes real-file-name)))
  1588.                      (or (nth 9 attr)
  1589.                      (not (file-ownership-preserved-p real-file-name))))))
  1590.               (condition-case ()
  1591.                   (copy-file real-file-name backupname t t)
  1592.                 (file-error
  1593.                  ;; If copying fails because file BACKUPNAME
  1594.                  ;; is not writable, delete that file and try again.
  1595.                  (if (and (file-exists-p backupname)
  1596.                       (not (file-writable-p backupname)))
  1597.                  (delete-file backupname))
  1598.                  (copy-file real-file-name backupname t t)))
  1599.             ;; rename-file should delete old backup.
  1600.             (rename-file real-file-name backupname t)
  1601.             (setq setmodes (file-modes backupname)))
  1602.             (file-error
  1603.              ;; If trouble writing the backup, write it in ~.
  1604.              (setq backupname (expand-file-name
  1605.                        (convert-standard-filename
  1606.                     "~/%backup%~")))
  1607.              (message "Cannot write backup file; backing up in %s"
  1608.                   (file-name-nondirectory backupname))
  1609.              (sleep-for 1)
  1610.              (condition-case ()
  1611.              (copy-file real-file-name backupname t t)
  1612.                (file-error
  1613.             ;; If copying fails because file BACKUPNAME
  1614.             ;; is not writable, delete that file and try again.
  1615.             (if (and (file-exists-p backupname)
  1616.                  (not (file-writable-p backupname)))
  1617.                 (delete-file backupname))
  1618.             (copy-file real-file-name backupname t t)))))
  1619.           (setq buffer-backed-up t)
  1620.           ;; Now delete the old versions, if desired.
  1621.           (if delete-old-versions
  1622.               (while targets
  1623.             (condition-case ()
  1624.                 (delete-file (car targets))
  1625.               (file-error nil))
  1626.             (setq targets (cdr targets))))
  1627.           setmodes)
  1628.         (file-error nil))))))
  1629.  
  1630. (defun file-name-sans-versions (name &optional keep-backup-version)
  1631.   "Return FILENAME sans backup versions or strings.
  1632. This is a separate procedure so your site-init or startup file can
  1633. redefine it.
  1634. If the optional argument KEEP-BACKUP-VERSION is non-nil,
  1635. we do not remove backup version numbers, only true file version numbers."
  1636.   (let ((handler (find-file-name-handler name 'file-name-sans-versions)))
  1637.     (if handler
  1638.     (funcall handler 'file-name-sans-versions name keep-backup-version)
  1639.       (substring name 0
  1640.          (if (eq system-type 'vax-vms)
  1641.              ;; VMS version number is (a) semicolon, optional
  1642.              ;; sign, zero or more digits or (b) period, option
  1643.              ;; sign, zero or more digits, provided this is the
  1644.              ;; second period encountered outside of the
  1645.              ;; device/directory part of the file name.
  1646.              (or (string-match ";[-+]?[0-9]*\\'" name)
  1647.              (if (string-match "\\.[^]>:]*\\(\\.[-+]?[0-9]*\\)\\'"
  1648.                        name)
  1649.                  (match-beginning 1))
  1650.              (length name))
  1651.            (if keep-backup-version
  1652.                (length name)
  1653.              (or (string-match "\\.~[0-9.]+~\\'" name)
  1654.              (string-match "~\\'" name)
  1655.              (length name))))))))
  1656.  
  1657. (defun file-ownership-preserved-p (file)
  1658.   "Returns t if deleting FILE and rewriting it would preserve the owner."
  1659.   (let ((handler (find-file-name-handler file 'file-ownership-preserved-p)))
  1660.     (if handler
  1661.     (funcall handler 'file-ownership-preserved-p file)
  1662.       (let ((attributes (file-attributes file)))
  1663.     ;; Return t if the file doesn't exist, since it's true that no
  1664.     ;; information would be lost by an (attempted) delete and create.
  1665.     (or (null attributes)
  1666.         (= (nth 2 attributes) (user-uid)))))))
  1667.  
  1668. (defun file-name-sans-extension (filename)
  1669.   "Return FILENAME sans final \"extension\".
  1670. The extension, in a file name, is the part that follows the last `.'."
  1671.   (save-match-data
  1672.     (let ((file (file-name-sans-versions (file-name-nondirectory filename)))
  1673.       directory)
  1674.       (if (string-match "\\.[^.]*\\'" file)
  1675.       (if (setq directory (file-name-directory filename))
  1676.           (expand-file-name (substring file 0 (match-beginning 0))
  1677.                 directory)
  1678.         (substring file 0 (match-beginning 0)))
  1679.     filename))))
  1680.  
  1681. (defun make-backup-file-name (file)
  1682.   "Create the non-numeric backup file name for FILE.
  1683. This is a separate function so you can redefine it for customization."
  1684.   (if (and (eq system-type 'ms-dos)
  1685.        (not (msdos-long-file-names)))
  1686.       (let ((fn (file-name-nondirectory file)))
  1687.     (concat (file-name-directory file)
  1688.         (or
  1689.          (and (string-match "\\`[^.]+\\'" fn)
  1690.               (concat (match-string 0 fn) ".~"))
  1691.          (and (string-match "\\`[^.]+\\.\\(..?\\)?" fn)
  1692.               (concat (match-string 0 fn) "~")))))
  1693.     (concat file "~")))
  1694.  
  1695. (defun backup-file-name-p (file)
  1696.   "Return non-nil if FILE is a backup file name (numeric or not).
  1697. This is a separate function so you can redefine it for customization.
  1698. You may need to redefine `file-name-sans-versions' as well."
  1699.     (string-match "~\\'" file))
  1700.  
  1701. ;; This is used in various files.
  1702. ;; The usage of bv-length is not very clean,
  1703. ;; but I can't see a good alternative,
  1704. ;; so as of now I am leaving it alone.
  1705. (defun backup-extract-version (fn)
  1706.   "Given the name of a numeric backup file, return the backup number.
  1707. Uses the free variable `bv-length', whose value should be
  1708. the index in the name where the version number begins."
  1709.   (if (and (string-match "[0-9]+~$" fn bv-length)
  1710.        (= (match-beginning 0) bv-length))
  1711.       (string-to-int (substring fn bv-length -1))
  1712.       0))
  1713.  
  1714. ;; I believe there is no need to alter this behavior for VMS;
  1715. ;; since backup files are not made on VMS, it should not get called.
  1716. (defun find-backup-file-name (fn)
  1717.   "Find a file name for a backup file, and suggestions for deletions.
  1718. Value is a list whose car is the name for the backup file
  1719.  and whose cdr is a list of old versions to consider deleting now.
  1720. If the value is nil, don't make a backup."
  1721.   (let ((handler (find-file-name-handler fn 'find-backup-file-name)))
  1722.     ;; Run a handler for this function so that ange-ftp can refuse to do it.
  1723.     (if handler
  1724.     (funcall handler 'find-backup-file-name fn)
  1725.       (if (eq version-control 'never)
  1726.       (list (make-backup-file-name fn))
  1727.     (let* ((base-versions (concat (file-name-nondirectory fn) ".~"))
  1728.            (bv-length (length base-versions))
  1729.            possibilities
  1730.            (versions nil)
  1731.            (high-water-mark 0)
  1732.            (deserve-versions-p nil)
  1733.            (number-to-delete 0))
  1734.       (condition-case ()
  1735.           (setq possibilities (file-name-all-completions
  1736.                    base-versions
  1737.                    (file-name-directory fn))
  1738.             versions (sort (mapcar
  1739.                     (function backup-extract-version)
  1740.                     possibilities)
  1741.                    '<)
  1742.             high-water-mark (apply 'max 0 versions)
  1743.             deserve-versions-p (or version-control
  1744.                        (> high-water-mark 0))
  1745.             number-to-delete (- (length versions)
  1746.                     kept-old-versions kept-new-versions -1))
  1747.         (file-error
  1748.          (setq possibilities nil)))
  1749.       (if (not deserve-versions-p)
  1750.           (list (make-backup-file-name fn))
  1751.         (cons (concat fn ".~" (int-to-string (1+ high-water-mark)) "~")
  1752.           (if (and (> number-to-delete 0)
  1753.                ;; Delete nothing if there is overflow
  1754.                ;; in the number of versions to keep.
  1755.                (>= (+ kept-new-versions kept-old-versions -1) 0))
  1756.               (mapcar (function (lambda (n)
  1757.                       (concat fn ".~" (int-to-string n) "~")))
  1758.                   (let ((v (nthcdr kept-old-versions versions)))
  1759.                 (rplacd (nthcdr (1- number-to-delete) v) ())
  1760.                 v))))))))))
  1761.  
  1762. (defun file-nlinks (filename)
  1763.   "Return number of names file FILENAME has."
  1764.   (car (cdr (file-attributes filename))))
  1765.  
  1766. (defun file-relative-name (filename &optional directory)
  1767.   "Convert FILENAME to be relative to DIRECTORY (default: default-directory)."
  1768.   (setq filename (expand-file-name filename)
  1769.     directory (file-name-as-directory (expand-file-name
  1770.                        (or directory default-directory))))
  1771.   (let ((ancestor ""))
  1772.     (while (not (string-match (concat "^" (regexp-quote directory)) filename))
  1773.       (setq directory (file-name-directory (substring directory 0 -1))
  1774.         ancestor (concat "../" ancestor)))
  1775.     (concat ancestor (substring filename (match-end 0)))))
  1776.  
  1777. (defun save-buffer (&optional args)
  1778.   "Save current buffer in visited file if modified.  Versions described below.
  1779. By default, makes the previous version into a backup file
  1780.  if previously requested or if this is the first save.
  1781. With 1 \\[universal-argument], marks this version
  1782.  to become a backup when the next save is done.
  1783. With 2 \\[universal-argument]'s,
  1784.  unconditionally makes the previous version into a backup file.
  1785. With 3 \\[universal-argument]'s, marks this version
  1786.  to become a backup when the next save is done,
  1787.  and unconditionally makes the previous version into a backup file.
  1788.  
  1789. With argument of 0, never makes the previous version into a backup file.
  1790.  
  1791. If a file's name is FOO, the names of its numbered backup versions are
  1792.  FOO.~i~ for various integers i.  A non-numbered backup file is called FOO~.
  1793. Numeric backups (rather than FOO~) will be made if value of
  1794.  `version-control' is not the atom `never' and either there are already
  1795.  numeric versions of the file being backed up, or `version-control' is
  1796.  non-nil.
  1797. We don't want excessive versions piling up, so there are variables
  1798.  `kept-old-versions', which tells Emacs how many oldest versions to keep,
  1799.  and `kept-new-versions', which tells how many newest versions to keep.
  1800.  Defaults are 2 old versions and 2 new.
  1801. `dired-kept-versions' controls dired's clean-directory (.) command.
  1802. If `delete-old-versions' is nil, system will query user
  1803.  before trimming versions.  Otherwise it does it silently."
  1804.   (interactive "p")
  1805.   (let ((modp (buffer-modified-p))
  1806.     (large (> (buffer-size) 50000))
  1807.     (make-backup-files (or (and make-backup-files (not (eq args 0)))
  1808.                    (memq args '(16 64)))))
  1809.     (and modp (memq args '(16 64)) (setq buffer-backed-up nil))
  1810.     (if (and modp large) (message "Saving file %s..." (buffer-file-name)))
  1811.     (basic-save-buffer)
  1812.     (and modp (memq args '(4 64)) (setq buffer-backed-up nil))))
  1813.  
  1814. (defun delete-auto-save-file-if-necessary (&optional force)
  1815.   "Delete auto-save file for current buffer if `delete-auto-save-files' is t.
  1816. Normally delete only if the file was written by this Emacs since
  1817. the last real save, but optional arg FORCE non-nil means delete anyway."
  1818.   (and buffer-auto-save-file-name delete-auto-save-files
  1819.        (not (string= buffer-file-name buffer-auto-save-file-name))
  1820.        (or force (recent-auto-save-p))
  1821.        (progn
  1822.      (condition-case ()
  1823.          (delete-file buffer-auto-save-file-name)
  1824.        (file-error nil))
  1825.      (set-buffer-auto-saved))))
  1826.  
  1827. (defvar after-save-hook nil
  1828.   "Normal hook that is run after a buffer is saved to its file.")
  1829.  
  1830. (defun basic-save-buffer ()
  1831.   "Save the current buffer in its visited file, if it has been modified.
  1832. After saving the buffer, run `after-save-hook'."
  1833.   (interactive)
  1834.   (save-excursion
  1835.     ;; In an indirect buffer, save its base buffer instead.
  1836.     (if (buffer-base-buffer)
  1837.     (set-buffer (buffer-base-buffer)))
  1838.     (if (buffer-modified-p)
  1839.     (let ((recent-save (recent-auto-save-p))
  1840.           setmodes tempsetmodes)
  1841.       ;; On VMS, rename file and buffer to get rid of version number.
  1842.       (if (and (eq system-type 'vax-vms)
  1843.            (not (string= buffer-file-name
  1844.                  (file-name-sans-versions buffer-file-name))))
  1845.           (let (buffer-new-name)
  1846.         ;; Strip VMS version number before save.
  1847.         (setq buffer-file-name
  1848.               (file-name-sans-versions buffer-file-name))
  1849.         ;; Construct a (unique) buffer name to correspond.
  1850.         (let ((buf (create-file-buffer (downcase buffer-file-name))))
  1851.           (setq buffer-new-name (buffer-name buf))
  1852.           (kill-buffer buf))
  1853.         (rename-buffer buffer-new-name)))
  1854.       ;; If buffer has no file name, ask user for one.
  1855.       (or buffer-file-name
  1856.           (let ((filename
  1857.              (expand-file-name
  1858.               (read-file-name "File to save in: ") nil)))
  1859.         (and (file-exists-p filename)
  1860.              (or (y-or-n-p (format "File `%s' exists; overwrite? "
  1861.                        filename))
  1862.              (error "Canceled")))
  1863.         (set-visited-file-name filename)))
  1864.       (or (verify-visited-file-modtime (current-buffer))
  1865.           (not (file-exists-p buffer-file-name))
  1866.           (yes-or-no-p
  1867.            (format "%s has changed since visited or saved.  Save anyway? "
  1868.                (file-name-nondirectory buffer-file-name)))
  1869.           (error "Save not confirmed"))
  1870.       (save-restriction
  1871.         (widen)
  1872.         (and (> (point-max) 1)
  1873.          (/= (char-after (1- (point-max))) ?\n)
  1874.          (not (and (eq selective-display t)
  1875.                (= (char-after (1- (point-max))) ?\r)))
  1876.          (or (eq require-final-newline t)
  1877.              (and require-final-newline
  1878.               (y-or-n-p
  1879.                (format "Buffer %s does not end in newline.  Add one? "
  1880.                    (buffer-name)))))
  1881.          (save-excursion
  1882.            (goto-char (point-max))
  1883.            (insert ?\n)))
  1884.         (or (run-hook-with-args-until-success 'write-contents-hooks)
  1885.         (run-hook-with-args-until-success 'local-write-file-hooks)
  1886.         (run-hook-with-args-until-success 'write-file-hooks)
  1887.         ;; If a hook returned t, file is already "written".
  1888.         ;; Otherwise, write it the usual way now.
  1889.         (setq setmodes (basic-save-buffer-1)))
  1890.         (setq buffer-file-number
  1891.           (nthcdr 10 (file-attributes buffer-file-name)))
  1892.         (if setmodes
  1893.         (condition-case ()
  1894.             (set-file-modes buffer-file-name setmodes)
  1895.           (error nil))))
  1896.       ;; If the auto-save file was recent before this command,
  1897.       ;; delete it now.
  1898.       (delete-auto-save-file-if-necessary recent-save)
  1899.       ;; Support VC `implicit' locking.
  1900.       (vc-after-save)
  1901.       (run-hooks 'after-save-hook))
  1902.       (message "(No changes need to be saved)"))))
  1903.  
  1904. ;; This does the "real job" of writing a buffer into its visited file
  1905. ;; and making a backup file.  This is what is normally done
  1906. ;; but inhibited if one of write-file-hooks returns non-nil.
  1907. ;; It returns a value to store in setmodes.
  1908. (defun basic-save-buffer-1 ()
  1909.   (let (tempsetmodes setmodes)
  1910.     (if (not (file-writable-p buffer-file-name))
  1911.     (let ((dir (file-name-directory buffer-file-name)))
  1912.       (if (not (file-directory-p dir))
  1913.           (error "%s is not a directory" dir)
  1914.         (if (not (file-exists-p buffer-file-name))
  1915.         (error "Directory %s write-protected" dir)
  1916.           (if (yes-or-no-p
  1917.            (format "File %s is write-protected; try to save anyway? "
  1918.                (file-name-nondirectory
  1919.                 buffer-file-name)))
  1920.           (setq tempsetmodes t)
  1921.         (error "Attempt to save to a file which you aren't allowed to write"))))))
  1922.     (or buffer-backed-up
  1923.     (setq setmodes (backup-buffer)))
  1924.     (let ((dir (file-name-directory buffer-file-name)))
  1925.       (if (and file-precious-flag
  1926.            (file-writable-p dir))
  1927.       ;; If file is precious, write temp name, then rename it.
  1928.       ;; This requires write access to the containing dir,
  1929.       ;; which is why we don't try it if we don't have that access.
  1930.       (let ((realname buffer-file-name)
  1931.         tempname temp nogood i succeed
  1932.         (old-modtime (visited-file-modtime)))
  1933.         (setq i 0)
  1934.         (setq nogood t)
  1935.         ;; Find the temporary name to write under.
  1936.         (while nogood
  1937.           (setq tempname (format
  1938.                   (if (and (eq system-type 'ms-dos)
  1939.                        (not (msdos-long-file-names)))
  1940.                   "%s#%d.tm#" ; MSDOS limits files to 8+3
  1941.                 "%s#tmp#%d")
  1942.                   dir i))
  1943.           (setq nogood (file-exists-p tempname))
  1944.           (setq i (1+ i)))
  1945.         (unwind-protect
  1946.         (progn (clear-visited-file-modtime)
  1947.                (write-region (point-min) (point-max)
  1948.                      tempname nil realname
  1949.                      buffer-file-truename)
  1950.                (setq succeed t))
  1951.           ;; If writing the temp file fails,
  1952.           ;; delete the temp file.
  1953.           (or succeed
  1954.           (progn
  1955.             (delete-file tempname)
  1956.             (set-visited-file-modtime old-modtime))))
  1957.         ;; Since we have created an entirely new file
  1958.         ;; and renamed it, make sure it gets the
  1959.         ;; right permission bits set.
  1960.         (setq setmodes (file-modes buffer-file-name))
  1961.         ;; We succeeded in writing the temp file,
  1962.         ;; so rename it.
  1963.         (rename-file tempname buffer-file-name t))
  1964.     ;; If file not writable, see if we can make it writable
  1965.     ;; temporarily while we write it.
  1966.     ;; But no need to do so if we have just backed it up
  1967.     ;; (setmodes is set) because that says we're superseding.
  1968.     (cond ((and tempsetmodes (not setmodes))
  1969.            ;; Change the mode back, after writing.
  1970.            (setq setmodes (file-modes buffer-file-name))
  1971.            (set-file-modes buffer-file-name 511)))
  1972.     (write-region (point-min) (point-max)
  1973.               buffer-file-name nil t buffer-file-truename)))
  1974.     setmodes))
  1975.  
  1976. (defun save-some-buffers (&optional arg exiting)
  1977.   "Save some modified file-visiting buffers.  Asks user about each one.
  1978. Optional argument (the prefix) non-nil means save all with no questions.
  1979. Optional second argument EXITING means ask about certain non-file buffers
  1980.  as well as about file buffers."
  1981.   (interactive "P")
  1982.   (save-window-excursion
  1983.     (let* ((queried nil)
  1984.        (files-done
  1985.         (map-y-or-n-p
  1986.          (function
  1987.           (lambda (buffer)
  1988.         (and (buffer-modified-p buffer)
  1989.              (not (buffer-base-buffer buffer))
  1990.              (or
  1991.               (buffer-file-name buffer)
  1992.               (and exiting
  1993.                (progn
  1994.                  (set-buffer buffer)
  1995.                  (and buffer-offer-save (> (buffer-size) 0)))))
  1996.              (if arg
  1997.              t
  1998.                (setq queried t)
  1999.                (if (buffer-file-name buffer)
  2000.                (format "Save file %s? "
  2001.                    (buffer-file-name buffer))
  2002.              (format "Save buffer %s? "
  2003.                  (buffer-name buffer)))))))
  2004.          (function
  2005.           (lambda (buffer)
  2006.         (set-buffer buffer)
  2007.         (save-buffer)))
  2008.          (buffer-list)
  2009.          '("buffer" "buffers" "save")
  2010.          (list (list ?\C-r (lambda (buf)
  2011.                  (view-buffer buf)
  2012.                  (setq view-exit-action
  2013.                        '(lambda (ignore)
  2014.                       (exit-recursive-edit)))
  2015.                  (recursive-edit)
  2016.                  ;; Return nil to ask about BUF again.
  2017.                  nil)
  2018.              "display the current buffer"))))
  2019.        (abbrevs-done
  2020.         (and save-abbrevs abbrevs-changed
  2021.          (progn
  2022.            (if (or arg
  2023.                (y-or-n-p (format "Save abbrevs in %s? "
  2024.                          abbrev-file-name)))
  2025.                (write-abbrev-file nil))
  2026.            ;; Don't keep bothering user if he says no.
  2027.            (setq abbrevs-changed nil)
  2028.            t))))
  2029.       (or queried (> files-done 0) abbrevs-done
  2030.       (message "(No files need saving)")))))
  2031.  
  2032. (defun not-modified (&optional arg)
  2033.   "Mark current buffer as unmodified, not needing to be saved.
  2034. With prefix arg, mark buffer as modified, so \\[save-buffer] will save.
  2035.  
  2036. It is not a good idea to use this function in Lisp programs, because it
  2037. prints a message in the minibuffer.  Instead, use `set-buffer-modified-p'."
  2038.   (interactive "P")
  2039.   (message (if arg "Modification-flag set"
  2040.            "Modification-flag cleared"))
  2041.   (set-buffer-modified-p arg))
  2042.  
  2043. (defun toggle-read-only (&optional arg)
  2044.   "Change whether this buffer is visiting its file read-only.
  2045. With arg, set read-only iff arg is positive."
  2046.   (interactive "P")
  2047.   (setq buffer-read-only
  2048.     (if (null arg)
  2049.             (not buffer-read-only)
  2050.             (> (prefix-numeric-value arg) 0)))
  2051.   (force-mode-line-update))
  2052.  
  2053. (defun insert-file (filename)
  2054.   "Insert contents of file FILENAME into buffer after point.
  2055. Set mark after the inserted text.
  2056.  
  2057. This function is meant for the user to run interactively.
  2058. Don't call it from programs!  Use `insert-file-contents' instead.
  2059. \(Its calling sequence is different; see its documentation)."
  2060.   (interactive "*fInsert file: ")
  2061.   (if (file-directory-p filename)
  2062.       (signal 'file-error (list "Opening input file" "file is a directory"
  2063.                 filename)))
  2064.   (let ((tem (insert-file-contents filename)))
  2065.     (push-mark (+ (point) (car (cdr tem))))))
  2066.  
  2067. (defun append-to-file (start end filename)
  2068.   "Append the contents of the region to the end of file FILENAME.
  2069. When called from a function, expects three arguments,
  2070. START, END and FILENAME.  START and END are buffer positions
  2071. saying what text to write."
  2072.   (interactive "r\nFAppend to file: ")
  2073.   (write-region start end filename t))
  2074.  
  2075. (defun file-newest-backup (filename)
  2076.   "Return most recent backup file for FILENAME or nil if no backups exist."
  2077.   (let* ((filename (expand-file-name filename))
  2078.      (file (file-name-nondirectory filename))
  2079.      (dir  (file-name-directory    filename))
  2080.      (comp (file-name-all-completions file dir))
  2081.          (newest nil)
  2082.          tem)
  2083.     (while comp
  2084.       (setq tem (car comp)
  2085.         comp (cdr comp))
  2086.       (cond ((and (backup-file-name-p tem)
  2087.                   (string= (file-name-sans-versions tem) file))
  2088.              (setq tem (concat dir tem))
  2089.              (if (or (null newest)
  2090.                      (file-newer-than-file-p tem newest))
  2091.                  (setq newest tem)))))
  2092.     newest))
  2093.  
  2094. (defun rename-uniquely ()
  2095.   "Rename current buffer to a similar name not already taken.
  2096. This function is useful for creating multiple shell process buffers
  2097. or multiple mail buffers, etc."
  2098.   (interactive)
  2099.   (save-match-data
  2100.     (let* ((base-name (if (and (string-match "<[0-9]+>\\'" (buffer-name))
  2101.                    (not (and buffer-file-name
  2102.                      (string= (buffer-name)
  2103.                           (file-name-nondirectory
  2104.                            buffer-file-name)))))
  2105.               ;; If the existing buffer name has a <NNN>,
  2106.               ;; which isn't part of the file name (if any),
  2107.               ;; then get rid of that.
  2108.               (substring (buffer-name) 0 (match-beginning 0))
  2109.             (buffer-name)))
  2110.        (new-buf (generate-new-buffer base-name))
  2111.        (name (buffer-name new-buf)))
  2112.       (kill-buffer new-buf)
  2113.       (rename-buffer name)
  2114.       (force-mode-line-update))))
  2115.  
  2116. (defun make-directory (dir &optional parents)
  2117.   "Create the directory DIR and any nonexistent parent dirs.
  2118. Interactively, the default choice of directory to create
  2119. is the current default directory for file names.
  2120. That is useful when you have visited a file in a nonexistent directory.
  2121.  
  2122. Noninteractively, the second (optional) argument PARENTS says whether
  2123. to create parent directories if they don't exist."
  2124.   (interactive
  2125.    (list (read-file-name "Make directory: " default-directory default-directory
  2126.              nil nil)
  2127.      t))
  2128.   (let ((handler (find-file-name-handler dir 'make-directory)))
  2129.     (if handler
  2130.     (funcall handler 'make-directory dir parents)
  2131.       (if (not parents)
  2132.       (make-directory-internal dir)
  2133.     (let ((dir (directory-file-name (expand-file-name dir)))
  2134.           create-list)
  2135.       (while (not (file-exists-p dir))
  2136.         (setq create-list (cons dir create-list)
  2137.           dir (directory-file-name (file-name-directory dir))))
  2138.       (while create-list
  2139.         (make-directory-internal (car create-list))
  2140.         (setq create-list (cdr create-list))))))))
  2141.  
  2142. (put 'revert-buffer-function 'permanent-local t)
  2143. (defvar revert-buffer-function nil
  2144.   "Function to use to revert this buffer, or nil to do the default.
  2145. The function receives two arguments IGNORE-AUTO and NOCONFIRM,
  2146. which are the arguments that `revert-buffer' received.")
  2147.  
  2148. (put 'revert-buffer-insert-file-contents-function 'permanent-local t)
  2149. (defvar revert-buffer-insert-file-contents-function nil
  2150.   "Function to use to insert contents when reverting this buffer.
  2151. Gets two args, first the nominal file name to use,
  2152. and second, t if reading the auto-save file.")
  2153.  
  2154. (defvar before-revert-hook nil
  2155.   "Normal hook for `revert-buffer' to run before reverting.
  2156. If `revert-buffer-function' is used to override the normal revert
  2157. mechanism, this hook is not used.")
  2158.  
  2159. (defvar after-revert-hook nil
  2160.   "Normal hook for `revert-buffer' to run after reverting.
  2161. Note that the hook value that it runs is the value that was in effect
  2162. before reverting; that makes a difference if you have buffer-local
  2163. hook functions.
  2164.  
  2165. If `revert-buffer-function' is used to override the normal revert
  2166. mechanism, this hook is not used.")
  2167.  
  2168. (defun revert-buffer (&optional ignore-auto noconfirm preserve-modes)
  2169.   "Replace the buffer text with the text of the visited file on disk.
  2170. This undoes all changes since the file was visited or saved.
  2171. With a prefix argument, offer to revert from latest auto-save file, if
  2172. that is more recent than the visited file.
  2173.  
  2174. When called from Lisp, the first argument is IGNORE-AUTO; only offer
  2175. to revert from the auto-save file when this is nil.  Note that the
  2176. sense of this argument is the reverse of the prefix argument, for the
  2177. sake of backward compatibility.  IGNORE-AUTO is optional, defaulting
  2178. to nil.
  2179.  
  2180. Optional second argument NOCONFIRM means don't ask for confirmation at
  2181. all.
  2182.  
  2183. If the value of `revert-buffer-function' is non-nil, it is called to
  2184. do the work.
  2185.  
  2186. The default revert function runs the hook `before-revert-hook' at the
  2187. beginning and `after-revert-hook' at the end."
  2188.   ;; I admit it's odd to reverse the sense of the prefix argument, but
  2189.   ;; there is a lot of code out there which assumes that the first
  2190.   ;; argument should be t to avoid consulting the auto-save file, and
  2191.   ;; there's no straightforward way to encourage authors to notice a
  2192.   ;; reversal of the argument sense.  So I'm just changing the user
  2193.   ;; interface, but leaving the programmatic interface the same.
  2194.   (interactive (list (not current-prefix-arg)))
  2195.   (if revert-buffer-function
  2196.       (funcall revert-buffer-function ignore-auto noconfirm)
  2197.     (let* ((opoint (point))
  2198.        (auto-save-p (and (not ignore-auto)
  2199.                  (recent-auto-save-p)
  2200.                  buffer-auto-save-file-name
  2201.                  (file-readable-p buffer-auto-save-file-name)
  2202.                  (y-or-n-p
  2203.    "Buffer has been auto-saved recently.  Revert from auto-save file? ")))
  2204.        (file-name (if auto-save-p
  2205.               buffer-auto-save-file-name
  2206.             buffer-file-name)))
  2207.       (cond ((null file-name)
  2208.          (error "Buffer does not seem to be associated with any file"))
  2209.         ((or noconfirm
  2210.          (yes-or-no-p (format "Revert buffer from file %s? "
  2211.                       file-name)))
  2212.          (run-hooks 'before-revert-hook)
  2213.          ;; If file was backed up but has changed since,
  2214.          ;; we shd make another backup.
  2215.          (and (not auto-save-p)
  2216.           (not (verify-visited-file-modtime (current-buffer)))
  2217.           (setq buffer-backed-up nil))
  2218.          ;; Get rid of all undo records for this buffer.
  2219.          (or (eq buffer-undo-list t)
  2220.          (setq buffer-undo-list nil))
  2221.          ;; Effectively copy the after-revert-hook status,
  2222.          ;; since after-find-file will clobber it.
  2223.          (let ((global-hook (default-value 'after-revert-hook))
  2224.            (local-hook-p (local-variable-p 'after-revert-hook))
  2225.            (local-hook (and (local-variable-p 'after-revert-hook)
  2226.                     after-revert-hook)))
  2227.            (let (buffer-read-only
  2228.              ;; Don't make undo records for the reversion.
  2229.              (buffer-undo-list t))
  2230.          (if revert-buffer-insert-file-contents-function
  2231.              (funcall revert-buffer-insert-file-contents-function
  2232.                   file-name auto-save-p)
  2233.            (if (not (file-exists-p file-name))
  2234.                (error "File %s no longer exists!" file-name))
  2235.            ;; Bind buffer-file-name to nil
  2236.            ;; so that we don't try to lock the file.
  2237.            (let ((buffer-file-name nil))
  2238.              (or auto-save-p
  2239.              (unlock-buffer)))
  2240.            (widen)
  2241.            (insert-file-contents file-name (not auto-save-p)
  2242.                      nil nil t)))
  2243.            (goto-char (min opoint (point-max)))
  2244.            ;; Recompute the truename in case changes in symlinks
  2245.            ;; have changed the truename.
  2246.            (setq buffer-file-truename
  2247.              (abbreviate-file-name (file-truename buffer-file-name)))
  2248.            (after-find-file nil nil t t preserve-modes)
  2249.            ;; Run after-revert-hook as it was before we reverted.
  2250.            (setq-default revert-buffer-internal-hook global-hook)
  2251.            (if local-hook-p
  2252.            (progn
  2253.              (make-local-variable 'revert-buffer-internal-hook)
  2254.              (setq revert-buffer-internal-hook local-hook))
  2255.          (kill-local-variable 'revert-buffer-internal-hook))
  2256.            (run-hooks 'revert-buffer-internal-hook))
  2257.          t)))))
  2258.  
  2259. (defun recover-file (file)
  2260.   "Visit file FILE, but get contents from its last auto-save file."
  2261.   ;; Actually putting the file name in the minibuffer should be used
  2262.   ;; only rarely.
  2263.   ;; Not just because users often use the default.
  2264.   (interactive "FRecover file: ")
  2265.   (setq file (expand-file-name file))
  2266.   (if (auto-save-file-name-p (file-name-nondirectory file))
  2267.       (error "%s is an auto-save file" file))
  2268.   (let ((file-name (let ((buffer-file-name file))
  2269.              (make-auto-save-file-name))))
  2270.     (cond ((if (file-exists-p file)
  2271.            (not (file-newer-than-file-p file-name file))
  2272.          (not (file-exists-p file-name)))
  2273.        (error "Auto-save file %s not current" file-name))
  2274.       ((save-window-excursion
  2275.          (if (not (eq system-type 'vax-vms))
  2276.          (with-output-to-temp-buffer "*Directory*"
  2277.            (buffer-disable-undo standard-output)
  2278.            (call-process "ls" nil standard-output nil
  2279.                  (if (file-symlink-p file) "-lL" "-l")
  2280.                  file file-name)))
  2281.          (yes-or-no-p (format "Recover auto save file %s? " file-name)))
  2282.        (switch-to-buffer (find-file-noselect file t))
  2283.        (let ((buffer-read-only nil))
  2284.          (erase-buffer)
  2285.          (insert-file-contents file-name nil))
  2286.        (after-find-file nil nil t))
  2287.       (t (error "Recover-file cancelled.")))))
  2288.  
  2289. (defun recover-session ()
  2290.   "Recover auto save files from a previous Emacs session.
  2291. This command first displays a Dired buffer showing you the
  2292. previous sessions that you could recover from.
  2293. To choose one, move point to the proper line and then type C-c C-c.
  2294. Then you'll be asked about a number of files to recover."
  2295.   (interactive)
  2296.   (let ((ls-lisp-support-shell-wildcards t))
  2297.     (dired (concat auto-save-list-file-prefix "*")))
  2298.   (goto-char (point-min))
  2299.   (or (looking-at "Move to the session you want to recover,")
  2300.       (let ((inhibit-read-only t))
  2301.     (insert "Move to the session you want to recover,\n"
  2302.         "then type C-c C-c to select it.\n\n"
  2303.         "You can also delete some of these files;\n"
  2304.         "type d on a line to mark that file for deletion.\n\n")))
  2305.   (use-local-map (nconc (make-sparse-keymap) (current-local-map)))
  2306.   (define-key (current-local-map) "\C-c\C-c" 'recover-session-finish))
  2307.  
  2308. (defun recover-session-finish ()
  2309.   "Choose one saved session to recover auto-save files from.
  2310. This command is used in the special Dired buffer created by
  2311. \\[recover-session]."
  2312.   (interactive)
  2313.   ;; Get the name of the session file to recover from.
  2314.   (let ((file (dired-get-filename))
  2315.     files
  2316.     (buffer (get-buffer-create " *recover*")))
  2317.     (dired-do-flagged-delete t)
  2318.     (unwind-protect
  2319.     (save-excursion
  2320.       ;; Read in the auto-save-list file.
  2321.       (set-buffer buffer)
  2322.       (erase-buffer)
  2323.       (insert-file-contents file)
  2324.       ;; Loop thru the text of that file
  2325.       ;; and get out the names of the files to recover.
  2326.       (while (not (eobp))
  2327.         (let (thisfile autofile)
  2328.           (if (eolp)
  2329.           ;; This is a pair of lines for a non-file-visiting buffer.
  2330.           ;; Get the auto-save file name and manufacture
  2331.           ;; a "visited file name" from that.
  2332.           (progn
  2333.             (forward-line 1)
  2334.             (setq autofile
  2335.               (buffer-substring-no-properties
  2336.                (point)
  2337.                (save-excursion
  2338.                  (end-of-line)
  2339.                  (point))))
  2340.             (setq thisfile
  2341.               (expand-file-name
  2342.                (substring
  2343.                 (file-name-nondirectory autofile)
  2344.                 1 -1)
  2345.                (file-name-directory autofile)))
  2346.             (forward-line 1))
  2347.         ;; This pair of lines is a file-visiting
  2348.         ;; buffer.  Use the visited file name.
  2349.         (progn
  2350.           (setq thisfile
  2351.             (buffer-substring-no-properties
  2352.              (point) (progn (end-of-line) (point))))
  2353.           (forward-line 1)
  2354.           (setq autofile
  2355.             (buffer-substring-no-properties
  2356.              (point) (progn (end-of-line) (point))))
  2357.           (forward-line 1)))
  2358.           ;; Ignore a file if its auto-save file does not exist now.
  2359.           (if (file-exists-p autofile)
  2360.           (setq files (cons thisfile files)))))
  2361.       (setq files (nreverse files))
  2362.       ;; The file contains a pair of line for each auto-saved buffer.
  2363.       ;; The first line of the pair contains the visited file name
  2364.       ;; or is empty if the buffer was not visiting a file.
  2365.       ;; The second line is the auto-save file name.
  2366.       (if files
  2367.           (map-y-or-n-p  "Recover %s? "
  2368.                  (lambda (file)
  2369.                    (condition-case nil
  2370.                    (save-excursion (recover-file file))
  2371.                  (error
  2372.                   "Failed to recover `%s'" file)))
  2373.                  files
  2374.                  '("file" "files" "recover"))
  2375.         (message "No files can be recovered from this session now")))
  2376.       (kill-buffer buffer))))
  2377.  
  2378. (defun kill-some-buffers ()
  2379.   "For each buffer, ask whether to kill it."
  2380.   (interactive)
  2381.   (let ((list (buffer-list)))
  2382.     (while list
  2383.       (let* ((buffer (car list))
  2384.          (name (buffer-name buffer)))
  2385.     (and (not (string-equal name ""))
  2386.          (/= (aref name 0) ? )
  2387.          (yes-or-no-p
  2388.           (format "Buffer %s %s.  Kill? "
  2389.               name
  2390.               (if (buffer-modified-p buffer)
  2391.               "HAS BEEN EDITED" "is unmodified")))
  2392.          (kill-buffer buffer)))
  2393.       (setq list (cdr list)))))
  2394.  
  2395. (defun auto-save-mode (arg)
  2396.   "Toggle auto-saving of contents of current buffer.
  2397. With prefix argument ARG, turn auto-saving on if positive, else off."
  2398.   (interactive "P")
  2399.   (setq buffer-auto-save-file-name
  2400.         (and (if (null arg)
  2401.          (or (not buffer-auto-save-file-name)
  2402.              ;; If autosave is off because buffer has shrunk,
  2403.              ;; then toggling should turn it on.
  2404.              (< buffer-saved-size 0))
  2405.            (or (eq arg t) (listp arg) (and (integerp arg) (> arg 0))))
  2406.          (if (and buffer-file-name auto-save-visited-file-name
  2407.               (not buffer-read-only))
  2408.          buffer-file-name
  2409.            (make-auto-save-file-name))))
  2410.   ;; If -1 was stored here, to temporarily turn off saving,
  2411.   ;; turn it back on.
  2412.   (and (< buffer-saved-size 0)
  2413.        (setq buffer-saved-size 0))
  2414.   (if (interactive-p)
  2415.       (message "Auto-save %s (in this buffer)"
  2416.            (if buffer-auto-save-file-name "on" "off")))
  2417.   buffer-auto-save-file-name)
  2418.  
  2419. (defun rename-auto-save-file ()
  2420.   "Adjust current buffer's auto save file name for current conditions.
  2421. Also rename any existing auto save file, if it was made in this session."
  2422.   (let ((osave buffer-auto-save-file-name))
  2423.     (setq buffer-auto-save-file-name
  2424.       (make-auto-save-file-name))
  2425.     (if (and osave buffer-auto-save-file-name
  2426.          (not (string= buffer-auto-save-file-name buffer-file-name))
  2427.          (not (string= buffer-auto-save-file-name osave))
  2428.          (file-exists-p osave)
  2429.          (recent-auto-save-p))
  2430.     (rename-file osave buffer-auto-save-file-name t))))
  2431.  
  2432. (defun make-auto-save-file-name ()
  2433.   "Return file name to use for auto-saves of current buffer.
  2434. Does not consider `auto-save-visited-file-name' as that variable is checked
  2435. before calling this function.  You can redefine this for customization.
  2436. See also `auto-save-file-name-p'."
  2437.   (if buffer-file-name
  2438.       (if (and (eq system-type 'ms-dos)
  2439.            (not (msdos-long-file-names)))
  2440.       (let ((fn (file-name-nondirectory buffer-file-name)))
  2441.         (string-match "\\`\\([^.]+\\)\\(\\.\\(..?\\)?.?\\|\\)\\'" fn)
  2442.         (concat (file-name-directory buffer-file-name)
  2443.             "#" (match-string 1 fn) 
  2444.             "." (match-string 3 fn) "#"))
  2445.     (concat (file-name-directory buffer-file-name)
  2446.         "#"
  2447.         (file-name-nondirectory buffer-file-name)
  2448.         "#"))
  2449.  
  2450.     ;; Deal with buffers that don't have any associated files.  (Mail
  2451.     ;; mode tends to create a good number of these.)
  2452.  
  2453.     (let ((buffer-name (buffer-name))
  2454.       (limit 0))
  2455.       ;; Use technique from Sebastian Kremer's auto-save
  2456.       ;; package to turn slashes into \\!.  This ensures that
  2457.       ;; the auto-save buffer name is unique.
  2458.  
  2459.       (while (string-match "[/\\]" buffer-name limit)
  2460.     (setq buffer-name (concat (substring buffer-name 0 (match-beginning 0))
  2461.             (if (string= (substring buffer-name
  2462.                         (match-beginning 0)
  2463.                         (match-end 0))
  2464.                      "/")
  2465.                 "\\!"
  2466.               "\\\\")
  2467.             (substring buffer-name (match-end 0))))
  2468.     (setq limit (1+ (match-end 0))))
  2469.  
  2470.       (expand-file-name (format "#%s#%s#" buffer-name (make-temp-name ""))))))
  2471.  
  2472. (defun auto-save-file-name-p (filename)
  2473.   "Return non-nil if FILENAME can be yielded by `make-auto-save-file-name'.
  2474. FILENAME should lack slashes.  You can redefine this for customization."
  2475.   (string-match "^#.*#$" filename))
  2476.  
  2477. (defun wildcard-to-regexp (wildcard)
  2478.   "Given a shell file name pattern WILDCARD, return an equivalent regexp.
  2479. The generated regexp will match a filename iff the filename
  2480. matches that wildcard according to shell rules.  Only wildcards known
  2481. by `sh' are supported."
  2482.   (let* ((i (string-match "[[.*+\\^$?]" wildcard))
  2483.      ;; Copy the initial run of non-special characters.
  2484.      (result (substring wildcard 0 i))
  2485.      (len (length wildcard)))
  2486.     ;; If no special characters, we're almost done.
  2487.     (if i
  2488.     (while (< i len)
  2489.       (let ((ch (aref wildcard i))
  2490.         j)
  2491.         (setq
  2492.          result
  2493.          (concat result
  2494.              (cond
  2495.               ((eq ch ?\[)    ; [...] maps to regexp char class
  2496.                (progn
  2497.              (setq i (1+ i))
  2498.              (concat
  2499.               (cond
  2500.                ((eq (aref wildcard i) ?!) ; [!...] -> [^...]
  2501.                 (progn
  2502.                   (setq i (1+ i))
  2503.                   (if (eq (aref wildcard i) ?\])
  2504.                   (progn
  2505.                     (setq i (1+ i))
  2506.                     "[^]")
  2507.                 "[^")))
  2508.                ((eq (aref wildcard i) ?^)
  2509.                 ;; Found "[^".  Insert a `\0' character
  2510.                 ;; (which cannot happen in a filename)
  2511.                 ;; into the character class, so that `^'
  2512.                 ;; is not the first character after `[',
  2513.                 ;; and thus non-special in a regexp.
  2514.                 (progn
  2515.                   (setq i (1+ i))
  2516.                   "[\000^"))
  2517.                ((eq (aref wildcard i) ?\])
  2518.                 ;; I don't think `]' can appear in a
  2519.                 ;; character class in a wildcard, but
  2520.                 ;; let's be general here.
  2521.                 (progn
  2522.                   (setq i (1+ i))
  2523.                   "[]"))
  2524.                (t "["))
  2525.               (prog1    ; copy everything upto next `]'.
  2526.                   (substring wildcard
  2527.                      i
  2528.                      (setq j (string-match
  2529.                           "]" wildcard i)))
  2530.                 (setq i (if j (1- j) (1- len)))))))
  2531.               ((eq ch ?.)  "\\.")
  2532.               ((eq ch ?*)  "[^\000]*")
  2533.               ((eq ch ?+)  "\\+")
  2534.               ((eq ch ?^)  "\\^")
  2535.               ((eq ch ?$)  "\\$")
  2536.               ((eq ch ?\\) "\\\\") ; probably cannot happen...
  2537.               ((eq ch ??)  "[^\000]")
  2538.               (t (char-to-string ch)))))
  2539.         (setq i (1+ i)))))
  2540.     ;; Shell wildcards should match the entire filename,
  2541.     ;; not its part.  Make the regexp say so.
  2542.     (concat "\\`" result "\\'")))
  2543.  
  2544. (defconst list-directory-brief-switches
  2545.   (if (eq system-type 'vax-vms) "" "-CF")
  2546.   "*Switches for list-directory to pass to `ls' for brief listing,")
  2547.  
  2548. (defconst list-directory-verbose-switches
  2549.   (if (eq system-type 'vax-vms)
  2550.       "/PROTECTION/SIZE/DATE/OWNER/WIDTH=(OWNER:10)"
  2551.     "-l")
  2552.   "*Switches for list-directory to pass to `ls' for verbose listing,")
  2553.  
  2554. (defun list-directory (dirname &optional verbose)
  2555.   "Display a list of files in or matching DIRNAME, a la `ls'.
  2556. DIRNAME is globbed by the shell if necessary.
  2557. Prefix arg (second arg if noninteractive) means supply -l switch to `ls'.
  2558. Actions controlled by variables `list-directory-brief-switches'
  2559. and `list-directory-verbose-switches'."
  2560.   (interactive (let ((pfx current-prefix-arg))
  2561.          (list (read-file-name (if pfx "List directory (verbose): "
  2562.                      "List directory (brief): ")
  2563.                        nil default-directory nil)
  2564.                pfx)))
  2565.   (let ((switches (if verbose list-directory-verbose-switches
  2566.             list-directory-brief-switches)))
  2567.     (or dirname (setq dirname default-directory))
  2568.     (setq dirname (expand-file-name dirname))
  2569.     (with-output-to-temp-buffer "*Directory*"
  2570.       (buffer-disable-undo standard-output)
  2571.       (princ "Directory ")
  2572.       (princ dirname)
  2573.       (terpri)
  2574.       (save-excursion
  2575.     (set-buffer "*Directory*")
  2576.     (setq default-directory
  2577.           (if (file-directory-p dirname)
  2578.           (file-name-as-directory dirname)
  2579.         (file-name-directory dirname)))
  2580.     (let ((wildcard (not (file-directory-p dirname))))
  2581.       (insert-directory dirname switches wildcard (not wildcard)))))))
  2582.  
  2583. (defvar insert-directory-program "ls"
  2584.   "Absolute or relative name of the `ls' program used by `insert-directory'.")
  2585.  
  2586. ;; insert-directory
  2587. ;; - must insert _exactly_one_line_ describing FILE if WILDCARD and
  2588. ;;   FULL-DIRECTORY-P is nil.
  2589. ;;   The single line of output must display FILE's name as it was
  2590. ;;   given, namely, an absolute path name.
  2591. ;; - must insert exactly one line for each file if WILDCARD or
  2592. ;;   FULL-DIRECTORY-P is t, plus one optional "total" line
  2593. ;;   before the file lines, plus optional text after the file lines.
  2594. ;;   Lines are delimited by "\n", so filenames containing "\n" are not
  2595. ;;   allowed.
  2596. ;;   File lines should display the basename.
  2597. ;; - must be consistent with
  2598. ;;   - functions dired-move-to-filename, (these two define what a file line is)
  2599. ;;            dired-move-to-end-of-filename,
  2600. ;;         dired-between-files, (shortcut for (not (dired-move-to-filename)))
  2601. ;;            dired-insert-headerline
  2602. ;;            dired-after-subdir-garbage (defines what a "total" line is)
  2603. ;;   - variable dired-subdir-regexp
  2604. (defun insert-directory (file switches &optional wildcard full-directory-p)
  2605.   "Insert directory listing for FILE, formatted according to SWITCHES.
  2606. Leaves point after the inserted text.
  2607. SWITCHES may be a string of options, or a list of strings.
  2608. Optional third arg WILDCARD means treat FILE as shell wildcard.
  2609. Optional fourth arg FULL-DIRECTORY-P means file is a directory and
  2610. switches do not contain `d', so that a full listing is expected.
  2611.  
  2612. This works by running a directory listing program
  2613. whose name is in the variable `insert-directory-program'.
  2614. If WILDCARD, it also runs the shell specified by `shell-file-name'."
  2615.   ;; We need the directory in order to find the right handler.
  2616.   (let ((handler (find-file-name-handler (expand-file-name file)
  2617.                      'insert-directory)))
  2618.     (if handler
  2619.     (funcall handler 'insert-directory file switches
  2620.          wildcard full-directory-p)
  2621.       (if (eq system-type 'vax-vms)
  2622.       (vms-read-directory file switches (current-buffer))
  2623.     (if wildcard
  2624.         ;; Run ls in the directory of the file pattern we asked for.
  2625.         (let ((default-directory
  2626.             (if (file-name-absolute-p file)
  2627.             (file-name-directory file)
  2628.               (file-name-directory (expand-file-name file))))
  2629.           (pattern (file-name-nondirectory file))
  2630.           (beg 0))
  2631.           ;; Quote some characters that have special meanings in shells;
  2632.           ;; but don't quote the wildcards--we want them to be special.
  2633.           ;; We also currently don't quote the quoting characters
  2634.           ;; in case people want to use them explicitly to quote
  2635.           ;; wildcard characters.
  2636.           (while (string-match "[ \t\n;<>&|()#$]" pattern beg)
  2637.         (setq pattern
  2638.               (concat (substring pattern 0 (match-beginning 0))
  2639.                   "\\"
  2640.                   (substring pattern (match-beginning 0)))
  2641.               beg (1+ (match-end 0))))
  2642.           (call-process shell-file-name nil t nil
  2643.                 "-c" (concat "\\"  ;; Disregard shell aliases!
  2644.                      insert-directory-program
  2645.                      " -d "
  2646.                      (if (stringp switches)
  2647.                          switches
  2648.                        (mapconcat 'identity switches " "))
  2649.                      " "
  2650.                      pattern)))
  2651.       ;; SunOS 4.1.3, SVr4 and others need the "." to list the
  2652.       ;; directory if FILE is a symbolic link.
  2653.       (apply 'call-process
  2654.          insert-directory-program nil t nil
  2655.          (let (list)
  2656.            (if (listp switches)
  2657.                (setq list switches)
  2658.              (if (not (equal switches ""))
  2659.              (progn
  2660.                ;; Split the switches at any spaces
  2661.                ;; so we can pass separate options as separate args.
  2662.                (while (string-match " " switches)
  2663.                  (setq list (cons (substring switches 0 (match-beginning 0))
  2664.                           list)
  2665.                    switches (substring switches (match-end 0))))
  2666.                (setq list (nreverse (cons switches list))))))
  2667.            (append list
  2668.                (list
  2669.                 (if full-directory-p
  2670.                 (concat (file-name-as-directory file) ".")
  2671.                   file))))))))))
  2672.  
  2673. (defvar kill-emacs-query-functions nil
  2674.   "Functions to call with no arguments to query about killing Emacs.
  2675. If any of these functions returns nil, killing Emacs is cancelled.
  2676. `save-buffers-kill-emacs' (\\[save-buffers-kill-emacs]) calls these functions,
  2677. but `kill-emacs', the low level primitive, does not.
  2678. See also `kill-emacs-hook'.")
  2679.  
  2680. (defun save-buffers-kill-emacs (&optional arg)
  2681.   "Offer to save each buffer, then kill this Emacs process.
  2682. With prefix arg, silently save all file-visiting buffers, then kill."
  2683.   (interactive "P")
  2684.   (save-some-buffers arg t)
  2685.   (and (or (not (memq t (mapcar (function
  2686.                   (lambda (buf) (and (buffer-file-name buf)
  2687.                              (buffer-modified-p buf))))
  2688.                 (buffer-list))))
  2689.        (yes-or-no-p "Modified buffers exist; exit anyway? "))
  2690.        (or (not (fboundp 'process-list))
  2691.        ;; process-list is not defined on VMS.
  2692.        (let ((processes (process-list))
  2693.          active)
  2694.          (while processes
  2695.            (and (memq (process-status (car processes)) '(run stop open))
  2696.             (let ((val (process-kill-without-query (car processes))))
  2697.               (process-kill-without-query (car processes) val)
  2698.               val)
  2699.             (setq active t))
  2700.            (setq processes (cdr processes)))
  2701.          (or (not active)
  2702.          (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
  2703.        ;; Query the user for other things, perhaps.
  2704.        (run-hook-with-args-until-failure 'kill-emacs-query-functions)
  2705.        (kill-emacs)))
  2706.  
  2707. (define-key ctl-x-map "\C-f" 'find-file)
  2708. (define-key ctl-x-map "\C-q" 'toggle-read-only)
  2709. (define-key ctl-x-map "\C-r" 'find-file-read-only)
  2710. (define-key ctl-x-map "\C-v" 'find-alternate-file)
  2711. (define-key ctl-x-map "\C-s" 'save-buffer)
  2712. (define-key ctl-x-map "s" 'save-some-buffers)
  2713. (define-key ctl-x-map "\C-w" 'write-file)
  2714. (define-key ctl-x-map "i" 'insert-file)
  2715. (define-key esc-map "~" 'not-modified)
  2716. (define-key ctl-x-map "\C-d" 'list-directory)
  2717. (define-key ctl-x-map "\C-c" 'save-buffers-kill-emacs)
  2718.  
  2719. (define-key ctl-x-4-map "f" 'find-file-other-window)
  2720. (define-key ctl-x-4-map "r" 'find-file-read-only-other-window)
  2721. (define-key ctl-x-4-map "\C-f" 'find-file-other-window)
  2722. (define-key ctl-x-4-map "b" 'switch-to-buffer-other-window)
  2723. (define-key ctl-x-4-map "\C-o" 'display-buffer)
  2724.  
  2725. (define-key ctl-x-5-map "b" 'switch-to-buffer-other-frame)
  2726. (define-key ctl-x-5-map "f" 'find-file-other-frame)
  2727. (define-key ctl-x-5-map "\C-f" 'find-file-other-frame)
  2728. (define-key ctl-x-5-map "r" 'find-file-read-only-other-frame)
  2729.  
  2730. ;;; files.el ends here
  2731.